package net.pokeranalytics.android.model.realm

import io.realm.RealmObject
import io.realm.annotations.Ignore
import io.realm.annotations.PrimaryKey
import net.pokeranalytics.android.R
import net.pokeranalytics.android.model.interfaces.Manageable
import net.pokeranalytics.android.ui.adapter.StaticRowRepresentableDataSource
import net.pokeranalytics.android.ui.view.RowRepresentable
import net.pokeranalytics.android.ui.view.RowViewType
import net.pokeranalytics.android.ui.view.rowrepresentable.TransactionRow
import java.util.*
import kotlin.collections.ArrayList


open class Transaction : RealmObject(), Manageable, StaticRowRepresentableDataSource, RowRepresentable {

	companion object {
		val rowRepresentation : List<RowRepresentable> by lazy {
			val rows = ArrayList<RowRepresentable>()
			rows.addAll(TransactionRow.values())
			rows
		}
	}

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

	// The bankroll of the transaction
	var bankroll: Bankroll? = null

    // The amount of the transaction
    var amount: Double = 0.0

    // The date of the transaction
    var date: Date = Date()

    // The type of the transaction
    var type: TransactionType? = null

    // A user comment
    var comment: String = ""

	@Ignore
	override val viewType: Int = RowViewType.ROW_TRANSACTION.ordinal

	override fun updateValue(value: Any?, row: RowRepresentable) {
		when(row) {
			TransactionRow.BANKROLL -> bankroll = value as Bankroll?
			TransactionRow.TYPE -> type = value as TransactionType?
			TransactionRow.AMOUNT -> amount = if (value == null) 0.0 else (value as String).toDouble()
			TransactionRow.COMMENT -> comment = value as String? ?: ""
			TransactionRow.DATE -> date = value as Date? ?: Date()
		}
	}

	override fun adapterRows(): List<RowRepresentable>? {
		return rowRepresentation
	}

	override fun isValidForSave(): Boolean {
		return bankroll != null && type != null && amount != 0.0
	}

	override fun getFailedSaveMessage(): Int {
		return if (bankroll == null) {
			R.string.no_br_popup_message
		} else if (type == null || amount == 0.0) {
			R.string.operation_empty_field_error
		} else {
			super.getFailedSaveMessage()
		}
	}

}

