package net.pokeranalytics.android.model.realm

import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
import net.pokeranalytics.android.R
import net.pokeranalytics.android.model.interfaces.CountableUsage
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.RowRepresentableEditDescriptor
import net.pokeranalytics.android.ui.view.rowrepresentable.FilterSubcategoryRow
import net.pokeranalytics.android.ui.view.rowrepresentable.GameRow
import net.pokeranalytics.android.ui.view.rowrepresentable.SimpleRow
import net.pokeranalytics.android.util.NULL_TEXT
import java.util.*
import kotlin.collections.ArrayList

open class Game : RealmObject(), Manageable, StaticRowRepresentableDataSource, RowRepresentable, CountableUsage {

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

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

	// The name of the game
	var name: String = ""

	// A shorter name for the game
	var shortName: String? = null

	// CountableUsage
	override var useCount: Int = 0

	override fun getDisplayName(): String {
		return this.name
	}

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

	override fun stringForRow(row: RowRepresentable): String {
		return when (row) {
			SimpleRow.NAME -> if (this.name.isNotEmpty()) this.name else NULL_TEXT
			GameRow.SHORT_NAME -> this.shortName ?: NULL_TEXT
			else -> return super.stringForRow(row)
		}
	}

	override fun editDescriptors(row: RowRepresentable): ArrayList<RowRepresentableEditDescriptor>? {
		return when (row) {
			SimpleRow.NAME -> row.editingDescriptors(mapOf("defaultValue" to this.name))
			GameRow.SHORT_NAME -> row.editingDescriptors(mapOf("defaultValue" to this.shortName))
			else -> null
		}
	}

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

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

	override fun getFailedSaveMessage(): Int {
		return R.string.variant_empty_name_error
	}

	/**
	 * Filters management
	 */

	override fun subcategoryRow(): FilterSubcategoryRow? {
		return FilterSubcategoryRow.GAME
	}

}
