package net.pokeranalytics.android.model.realm

import io.realm.RealmList
import io.realm.RealmObject
import io.realm.RealmResults
import io.realm.annotations.Ignore
import io.realm.annotations.LinkingObjects
import io.realm.annotations.RealmClass

@RealmClass
open class Result : RealmObject() {

	/**
	 * The buyin amount
 	 */
    var buyin: Double? = null
        set(value) {
            field = value
            this.computeNet()
        }

	/**
	 * The cashed out amount
 	 */
    var cashout: Double? = null
        set(value) {
            field = value
            this.computeNet()
        }

	/**
	 * The net result
	 */
	var netResult: Double? = null
		set(value) {
			field = value
			this.computeNet()
		}

	/**
	 * The pre-computed net (readonly)
	 */
	var net: Double = 0.0
		private set

	/**
	 * Tips
 	 */
	var tips: Double? = null

	// The transactions associated with the Result, impacting the result
    var transactions: RealmList<Transaction> = RealmList()
        set(value) {
            field = value
            this.computeNet()
        }

    // The tournament final position, if applicable
    var tournamentFinalPosition: Int? = null

	@LinkingObjects("result")
	private val sessions: RealmResults<Session>? = null

	@Ignore
	val session: Session? = this.sessions?.firstOrNull()

	/**
	 * Returns 1 if the session is positive
	 */
	@Ignore
	val isPositive: Int = if (this.net >= 0.0) 1 else 0

    // Computes the Net
    private fun computeNet() {

        val transactionsSum = transactions.sumByDouble { it.amount }
        this.netResult?.let {
            this.net = it + transactionsSum
        } ?: run {
            val buyin = this.buyin ?: 0.0
            val cashOut = this.cashout ?: 0.0
            this.net = cashOut - buyin + transactionsSum
        }

	    // Precompute results
		this.session?.updateComputableResult()
	    this.session?.sessionSet?.computeStats()
    }

	// @todo tips?

}