package net.pokeranalytics.android.ui.fragment.components.bottomsheet

import android.app.Activity
import android.content.Intent
import io.realm.RealmList
import io.realm.RealmModel
import net.pokeranalytics.android.exceptions.RowRepresentableEditDescriptorException
import net.pokeranalytics.android.model.LiveData
import net.pokeranalytics.android.ui.activity.EditableDataActivity
import net.pokeranalytics.android.ui.activity.components.PokerAnalyticsActivity
import net.pokeranalytics.android.ui.view.RowRepresentable
import net.pokeranalytics.android.ui.view.RowViewType

/**
 * Manage multiple items selection in a bottom sheet list
 */
open class BottomSheetMultiSelectionFragment : BottomSheetListFragment() {

	private val selectedRows: ArrayList<RowRepresentable> = ArrayList()

	override fun viewTypeForPosition(position: Int): Int {
		return RowViewType.TITLE_CHECK.ordinal
	}

	override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
		if (requestCode == REQUEST_CODE_ADD_NEW_OBJECT && resultCode == Activity.RESULT_OK && data != null) {
			val dataType = data.getIntExtra(EditableDataActivity.IntentKey.DATA_TYPE.keyName, 0)
			val primaryKey = data.getStringExtra(EditableDataActivity.IntentKey.PRIMARY_KEY.keyName)
			val pokerAnalyticsActivity = activity as PokerAnalyticsActivity
			val liveDataType = LiveData.values()[dataType]
			val proxyItem: RealmModel? = liveDataType.getData(pokerAnalyticsActivity.getRealm(), primaryKey)
			selectedRows.add(proxyItem as RowRepresentable)
			dataAdapter.refreshRow(proxyItem as RowRepresentable)
		}
	}

	override fun getValue(): Any? {
		return selectedRows
	}

	override fun onRowSelected(position: Int, row: RowRepresentable, fromAction: Boolean) {
		if (selectedRows.contains(row)) {
			selectedRows.remove(row)
		} else {
			selectedRows.add(row)
		}
		dataAdapter.refreshRow(row)
	}

	override fun isSelected(row: RowRepresentable): Boolean {
		return selectedRows.contains(row)
	}

	override fun initData() {
		super.initData()
		val bottomSheetData =
			getData() ?: throw RowRepresentableEditDescriptorException("RowRepresentableEditDescriptor not found")
		if (bottomSheetData.size != 1) {
			throw RowRepresentableEditDescriptorException("RowRepresentableEditDescriptor inconsistency")
		}
		bottomSheetData.first().defaultValue?.let {
			(it as RealmList<*>).forEach { row ->
				this.selectedRows.add(row as RowRepresentable)
			}
		}
	}
}