package net.pokeranalytics.android.ui.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import net.pokeranalytics.android.R
import net.pokeranalytics.android.ui.activity.components.PokerAnalyticsActivity
import net.pokeranalytics.android.ui.fragment.FiltersFragment
import net.pokeranalytics.android.ui.interfaces.FilterActivityRequestCode
import net.pokeranalytics.android.ui.interfaces.FilterableType

class FiltersActivity : PokerAnalyticsActivity() {

	enum class IntentKey(val keyName: String) {
		FILTER_ID("FILTER_ID"),
		FILTERABLE_TYPE("FILTERABLE_TYPE"),
		HIDE_MOST_USED_FILTERS("HIDE_MOST_USED_FILTERS"),
		;
	}

	private lateinit var fragment: FiltersFragment

	companion object {
		/**
		 * Create a new instance for result
		 */
		fun newInstanceForResult(fragment: Fragment, filterId: String? = null, currentFilterable: FilterableType, hideMostUsedFilters: Boolean = false) {
			val intent = getIntent(fragment.requireContext(), filterId, currentFilterable, hideMostUsedFilters)
			fragment.startActivityForResult(intent, FilterActivityRequestCode.CREATE_FILTER.ordinal)
		}

		private fun getIntent(context: Context, filterId: String?, currentFilterable: FilterableType, hideMostUsedFilters: Boolean = false): Intent {
			val intent = Intent(context, FiltersActivity::class.java)
			intent.putExtra(IntentKey.FILTERABLE_TYPE.keyName, currentFilterable.uniqueIdentifier)
			intent.putExtra(IntentKey.HIDE_MOST_USED_FILTERS.keyName, hideMostUsedFilters)
			filterId?.let {
				intent.putExtra(IntentKey.FILTER_ID.keyName, it)
			}
			return intent
		}
	}

	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		setContentView(R.layout.activity_filters)
		initUI()
	}

	override fun onBackPressed() {
		fragment.onBackPressed()
	}

	/**
	 * Init UI
	 */
	private fun initUI() {

		val fragmentManager = supportFragmentManager
		val fragmentTransaction = fragmentManager.beginTransaction()
		val filterId = intent.getStringExtra(IntentKey.FILTER_ID.keyName)
		val uniqueIdentifier= intent.getIntExtra(IntentKey.FILTERABLE_TYPE.keyName, 0)
		val hideMostUsedFilters = intent.getBooleanExtra(IntentKey.HIDE_MOST_USED_FILTERS.keyName, false)
		val filterableType = FilterableType.valueByIdentifier(uniqueIdentifier)

		fragment = FiltersFragment()
		fragmentTransaction.add(R.id.container, fragment)
		fragmentTransaction.commit()
		fragment.setData(filterId, filterableType)
		fragment.updateMostUsedFiltersVisibility(!hideMostUsedFilters)

	}

}