package net.pokeranalytics.android.ui.fragment.data

import net.pokeranalytics.android.model.realm.Transaction
import net.pokeranalytics.android.model.realm.TransactionType
import net.pokeranalytics.android.ui.adapter.RowRepresentableDataSource
import net.pokeranalytics.android.ui.view.RowRepresentable
import net.pokeranalytics.android.ui.view.RowRepresentableEditDescriptor
import net.pokeranalytics.android.ui.view.rowrepresentable.SimpleRow
import net.pokeranalytics.android.ui.view.rowrepresentable.TransactionTypeRow

class TransactionTypeDataFragment : EditableDataFragment(), RowRepresentableDataSource {

	val transactionType: TransactionType
		get() {
			return this.item as TransactionType
		}

	// RowRepresentableDataSource

	override fun adapterRows(): List<RowRepresentable>? {
		return this.transactionType.adapterRows()
	}

	override fun rowRepresentableForPosition(position: Int): RowRepresentable? {
		return this.transactionType.rowRepresentableForPosition(position)
	}

	override fun numberOfRows(): Int {
		return this.transactionType.numberOfRows()
	}

	override fun viewTypeForPosition(position: Int): Int {
		return this.transactionType.viewTypeForPosition(position)
	}

	override fun stringForRow(row: RowRepresentable): String {
		return when (row) {
			SimpleRow.NAME -> this.transactionType.name
			else -> return super.stringForRow(row)
		}
	}

	override fun boolForRow(row: RowRepresentable): Boolean {
		return when (row) {
			TransactionTypeRow.TRANSACTION_ADDITIVE -> this.transactionType.additive
			else -> super.boolForRow(row)
		}
	}

	override fun editDescriptors(row: RowRepresentable): ArrayList<RowRepresentableEditDescriptor>? {
		return row.editingDescriptors(mapOf("defaultValue" to this.transactionType.name))
	}

	override fun isEnabled(row: RowRepresentable): Boolean {
		return when (row) {
			TransactionTypeRow.TRANSACTION_ADDITIVE -> {
				return this.transactionType.isValidForDelete(getRealm())
			}
			else -> super.isEnabled(row)
		}
	}

	override fun isSelectable(row: RowRepresentable): Boolean {
		return when (row) {
			TransactionTypeRow.TRANSACTION_ADDITIVE -> {
				val realm = getRealm()
				val useCount = realm.where(Transaction::class.java)
					.equalTo("type.id", this.transactionType.id).findAll().size
				return useCount == 0
			}
			else -> super.isSelectable(row)
		}
	}

	override fun getDataSource(): RowRepresentableDataSource {
		return this
	}

}