package net.pokeranalytics.android.model.realm

import io.realm.Realm
import io.realm.RealmObject
import io.realm.RealmResults
import io.realm.annotations.Ignore
import io.realm.annotations.LinkingObjects
import net.pokeranalytics.android.model.interfaces.Timed
import java.util.*


open class SessionSet : RealmObject(), Timed {

	var startDate: Date = Date()
        set(value) {
            field = value
            this.computeNetDuration()
        }

    var endDate: Date = Date()
        set(value) {
            field = value
            this.computeNetDuration()
        }

	override fun startDate(): Date? {
		return this.startDate
	}

    override fun endDate(): Date {
        return this.endDate
    }

    override var breakDuration: Long = 0L
        set(value) {
            field = value
            this.computeNetDuration()
        }

	/**
	 * The start date of the break
	 */
	override var pauseDate: Date? = null

	/**
	 * the net duration of the set (READONLY)
	 */
    override var netDuration: Long = 0L

    companion object {

        fun newInstance(realm: Realm) : SessionSet {
            val sessionSet: SessionSet = realm.createObject(SessionSet::class.java)
            return realm.copyToRealm(sessionSet)
        }

    }

	fun computeStats() {
		this.ratedNet = this.sessions?.sumByDouble { it.computableResult?.ratedNet ?: 0.0 } ?: 0.0
		this.estimatedHands = this.sessions?.sumByDouble { it.estimatedHands } ?: 0.0
		this.bbNetResult = this.sessions?.sumByDouble { it.bbNetResult } ?: 0.0
	}

    /**
     * The list of endedSessions associated with this set
     */
    @LinkingObjects("sessionSet")
    val sessions: RealmResults<Session>? = null

//    @Ignore
    var ratedNet: Double = 0.0

    @Ignore
    val hourlyRate: Double = this.ratedNet / this.hourlyDuration

//    @Ignore
    var estimatedHands: Double = 0.0

//    @Ignore
    var bbNetResult: Double = 0.0

	enum class Field(val identifier: String) {
		RATED_NET("ratedNet"),
		HOURLY_RATE("hourlyRate"),
		BB_NET("bbNetResult"),
		ESTIMATED_HANDS("estimatedHands"),
		NET_DURATION("netDuration")
	}

}

