package net.pokeranalytics.android.ui.interfaces

import android.content.Context
import android.content.Intent
import androidx.fragment.app.Fragment
import io.realm.Realm
import io.realm.kotlin.where
import net.pokeranalytics.android.model.realm.Filter
import net.pokeranalytics.android.ui.activity.FiltersActivity
import net.pokeranalytics.android.util.Preferences
import net.pokeranalytics.android.util.enumerations.IntIdentifiable
import net.pokeranalytics.android.util.enumerations.IntSearchable

enum class FilterActivityRequestCode {
	SELECT_FILTER,
	CREATE_FILTER,
	;
}

enum class FilterableType(override var uniqueIdentifier: Int) : IntIdentifiable {
	ALL(0),
	SESSION(1),
	TRANSACTION(2),
	BANKROLL(3),
	HAND_HISTORY(4),
	;

	companion object : IntSearchable<FilterableType> {

		override fun valuesInternal(): Array<FilterableType> {
			return values()
		}
	}

}

interface FilterHandler {
	companion object {
		const val INTENT_FILTER_UPDATE_FILTER_UI = "net.pokeranalytics.android.UPDATE_FILTER_UI"
	}

	fun applyFilter()
	fun removeFilter()

	fun saveFilter(context: Context, filterId: String) {
		Preferences.setActiveFilterId(filterId, context)


		val realm = Realm.getDefaultInstance()
		realm.beginTransaction()
		currentFilter(context, realm)?.let {
			it.useCount++
		}
		realm.commitTransaction()
		realm.close()

		// Send broadcast
		val intent = Intent()
		intent.action = INTENT_FILTER_UPDATE_FILTER_UI
		context.sendBroadcast(intent)
	}

	fun currentFilter(context: Context, realm: Realm): Filter? {
		return Preferences.getActiveFilterId(context)?.let {
			realm.where<Filter>().equalTo("id", it).findFirst()
		} ?: run {
			null
		}
	}

	var currentFilterable: FilterableType


	/**
	 * Manage filters
	 */
	fun manageFilters(fragment: Fragment) {
		FiltersActivity.newInstanceForResult(fragment = fragment, currentFilterable = currentFilterable)
	}
}