package net.pokeranalytics.android.model.realm

import io.realm.RealmList
import io.realm.RealmObject
import io.realm.annotations.RealmClass

@RealmClass
open class Result : RealmObject() {

    // the user associated to this session result
    var player: Player? = null

    // 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 net (readonly)
    var net: Double = 0.0
        private set

    // 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

    // Computes the Net
    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
        }

    }

    // @todo tips?
}