package net.pokeranalytics.android.ui.fragment

import android.content.Intent
import android.os.Bundle
import android.view.*
import androidx.recyclerview.widget.LinearLayoutManager
import io.realm.RealmObject
import kotlinx.android.synthetic.main.fragment_editable_data.*
import kotlinx.android.synthetic.main.fragment_filters.view.*
import net.pokeranalytics.android.R
import net.pokeranalytics.android.ui.activity.FilterDetailsActivity
import net.pokeranalytics.android.ui.activity.components.PokerAnalyticsActivity
import net.pokeranalytics.android.ui.adapter.RowRepresentableAdapter
import net.pokeranalytics.android.ui.adapter.RowRepresentableDelegate
import net.pokeranalytics.android.ui.adapter.StaticRowRepresentableDataSource
import net.pokeranalytics.android.ui.fragment.components.PokerAnalyticsFragment
import net.pokeranalytics.android.ui.view.RowRepresentable
import net.pokeranalytics.android.ui.view.rowrepresentable.FilterCategoryRow
import timber.log.Timber


open class FiltersFragment : PokerAnalyticsFragment(), StaticRowRepresentableDataSource, RowRepresentableDelegate {

	companion object {
		const val REQUEST_CODE_FILTER_DETAILS = 100
	}

	lateinit var parentActivity: PokerAnalyticsActivity
	lateinit var item: RealmObject
	lateinit var rowRepresentableAdapter: RowRepresentableAdapter

	private var rows: ArrayList<RowRepresentable> = ArrayList()
	private var filterMenu: Menu? = null
	private var primaryKey: String? = null
	private var selectedRow: RowRepresentable? = null

	var isUpdating = false

	override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
		return inflater.inflate(R.layout.fragment_filters, container, false)
	}

	override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
		super.onViewCreated(view, savedInstanceState)
		initUI()
		initData()
	}

	override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
		super.onActivityResult(requestCode, resultCode, data)

		if (requestCode == REQUEST_CODE_FILTER_DETAILS) {

			Timber.d("onActivityResult: $requestCode")

			// TODO: Update the selected row here...
			selectedRow?.let {
				rowRepresentableAdapter.refreshRow(it)
			}
		}
	}

	override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
		inflater?.inflate(R.menu.editable_data, menu)
		this.filterMenu = menu
		updateMenuUI()
		super.onCreateOptionsMenu(menu, inflater)
	}

	override fun onBackPressed() {
		super.onBackPressed()

		//TODO: Cancel changes on the Filter object

		finishActivityWithResult("")
	}

	override fun onOptionsItemSelected(item: MenuItem?): Boolean {
		when (item!!.itemId) {
			R.id.save -> saveData()
			R.id.delete -> deleteData()
		}
		return true
	}

	override fun adapterRows(): List<RowRepresentable>? {
		return rows
	}

	override fun onRowSelected(position: Int, row: RowRepresentable, fromAction: Boolean) {
		super.onRowSelected(position, row, fromAction)

		if (row is FilterCategoryRow) {
			Timber.d("Subcategories: ${row.getSubcategories()}")
			selectedRow = row
			FilterDetailsActivity.newInstanceForResult(this, row.ordinal, REQUEST_CODE_FILTER_DETAILS)
		}

	}

	override fun onRowValueChanged(value: Any?, row: RowRepresentable) {
		super.onRowValueChanged(value, row)
	}

	/**
	 * Init UI
	 */
	private fun initUI() {
		parentActivity = activity as PokerAnalyticsActivity
		parentActivity.setSupportActionBar(toolbar)
		parentActivity.supportActionBar?.setDisplayHomeAsUpEnabled(true)
		setHasOptionsMenu(true)

		val viewManager = LinearLayoutManager(requireContext())

		recyclerView.apply {
			setHasFixedSize(true)
			layoutManager = viewManager
		}
	}

	/**
	 * Init data
	 */
	private fun initData() {

		this.appBar.toolbar.title = getString(R.string.filter)

		rows.addAll(FilterCategoryRow.values())

		this.rowRepresentableAdapter = RowRepresentableAdapter(this, this)
		this.recyclerView.adapter = rowRepresentableAdapter

	}

	/**
	 * Update menu UI
	 */
	private fun updateMenuUI() {
		filterMenu?.findItem(R.id.delete)?.isVisible = isUpdating
		filterMenu?.findItem(R.id.save)?.isVisible = true
	}

	/**
	 * Save data
	 */
	private fun saveData() {

		// TODO: Save the filter object here
		// Maybe we don't need to do anything because the object is already up to date

		finishActivityWithResult("")
	}

	/**
	 * Delete data
	 */
	private fun deleteData() {

		// TODO: Delete the filter object here

	}

	/**
	 * Finish the activity with a result
	 */
	private fun finishActivityWithResult(uniqueIdentifier: String) {
		/*
		val intent = Intent()
		intent.putExtra(EditableDataActivity.IntentKey.DATA_TYPE.keyName, dataType)
		intent.putExtra(EditableDataActivity.IntentKey.PRIMARY_KEY.keyName, uniqueIdentifier)
		activity?.setResult(RESULT_OK, intent)
		*/
		activity?.finish()
	}

	/**
	 * Set fragment data
	 */
	fun setData(primaryKey: String?) {
		this.primaryKey = primaryKey
	}

}