package net.pokeranalytics.android.model.realm

import android.text.InputType
import io.realm.RealmList
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
import net.pokeranalytics.android.model.ObjectSavable
import net.pokeranalytics.android.ui.adapter.components.LiveDataDataSource
import net.pokeranalytics.android.ui.adapter.components.RowRepresentableDataSource
import net.pokeranalytics.android.ui.fragment.components.bottomsheet.BottomSheetData
import net.pokeranalytics.android.ui.view.BankrollRow
import net.pokeranalytics.android.ui.view.RowEditable
import net.pokeranalytics.android.ui.view.RowRepresentable
import net.pokeranalytics.android.ui.view.SimpleRow
import java.util.*
import kotlin.collections.ArrayList

open class Bankroll(name: String = "") : RealmObject(), RowRepresentableDataSource, LiveDataDataSource,
    RowEditable, ObjectSavable {

    companion object {
        fun newInstance() : Bankroll {
            var bankroll: Bankroll = Bankroll()
            return bankroll
        }
    }

    @PrimaryKey
    var id = UUID.randomUUID().toString()

    // the name of the bankroll
    var name: String = name

    // Indicates whether the bankroll is live or online
    var live: Boolean = true

    // The list of transactions of the bankroll
    var transactions: RealmList<Transaction> = RealmList()

    // The currency of the bankroll
    var currency: Currency? = null

    // @todo rate management

    override val title: String get() = this.name
    override val primaryKey: String get() = this.id

    override fun adapterRows(): ArrayList<RowRepresentable> {
        val rows = ArrayList<RowRepresentable>()
        rows.add(SimpleRow.NAME)
        rows.addAll(BankrollRow.values())
        return rows
    }

    override fun stringForRow(row: RowRepresentable): String {
        return when (row) {
            SimpleRow.NAME -> this.name
            BankrollRow.LIVE -> if (this.live) "live" else "online"
            BankrollRow.CURRENCY -> this.currency?.code?: ""
            else -> return super.stringForRow(row)
        }
    }

    override fun boolForRow(row: RowRepresentable): Boolean {
        when (row) {
            BankrollRow.LIVE -> return true
            else -> return super.boolForRow(row)
        }
    }

    override fun getBottomSheetData(row: RowRepresentable): ArrayList<BottomSheetData> {
        val data = java.util.ArrayList<BottomSheetData>()
        when (row) {
            SimpleRow.NAME -> data.add(BottomSheetData(this.name, SimpleRow.NAME.resId, InputType.TYPE_CLASS_TEXT))
        }
        return data
    }

    override fun updateValue(value: Any?, row: RowRepresentable) {
        when (row) {
            SimpleRow.NAME -> this.name = value as String? ?: ""
        }
    }

    override fun isValidForSave(): Boolean {
        return this.name.isNotEmpty()
    }
}