package net.pokeranalytics.android.ui.fragment

import android.app.Activity.RESULT_OK
import android.content.Intent
import android.os.Bundle
import android.view.*
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.fragment_bankroll.*
import net.pokeranalytics.android.R
import net.pokeranalytics.android.calculus.ComputedStat
import net.pokeranalytics.android.calculus.Stat
import net.pokeranalytics.android.calculus.bankroll.BankrollReport
import net.pokeranalytics.android.model.LiveData
import net.pokeranalytics.android.ui.activity.DataListActivity
import net.pokeranalytics.android.ui.activity.EditableDataActivity
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.RowViewType
import net.pokeranalytics.android.ui.view.rowrepresentable.CustomizableRowRepresentable

class BankrollDetailsFragment : PokerAnalyticsFragment(), StaticRowRepresentableDataSource, RowRepresentableDelegate {

	companion object {

		const val REQUEST_CODE_EDIT = 1000

		/**
		 * Create new instance
		 */
		fun newInstance(bankrollReport: BankrollReport): BankrollDetailsFragment {
			val fragment = BankrollDetailsFragment()
			fragment.bankrollReport = bankrollReport
			return fragment
		}
	}

	private lateinit var bankrollAdapter: RowRepresentableAdapter
	private lateinit var bankrollReport: BankrollReport

	private var bankrollDetailsMenu: Menu? = null
	private var rows: ArrayList<RowRepresentable> = ArrayList()

	// Life Cycle

	override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
		return inflater.inflate(R.layout.fragment_bankroll_details, 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_EDIT && resultCode == RESULT_OK) {
			if (data?.getStringExtra(DataListActivity.IntentKey.ITEM_DELETED.keyName) != null) {
				activity?.setResult(RESULT_OK, data)
				activity?.finish()
			} else {
				updateMenuUI()
			}
		}
	}

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

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

	}

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

	override fun onOptionsItemSelected(item: MenuItem?): Boolean {
		when (item!!.itemId) {
			R.id.settings -> editBankroll()
		}
		return true
	}

	// Business

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

		rows.clear()

		rows.add(CustomizableRowRepresentable(RowViewType.HEADER_TITLE, resId = R.string.global))

		val totalComputedStat = ComputedStat(Stat.NET_RESULT, bankrollReport.total)
		val netComputedStat = ComputedStat(Stat.NET_RESULT, bankrollReport.netResult)
		val netBankedComputedStat = ComputedStat(Stat.NET_RESULT, bankrollReport.netBanked)

		rows.add(CustomizableRowRepresentable(RowViewType.TITLE_VALUE, resId = R.string.bankroll, computedStat = totalComputedStat))
		rows.add(CustomizableRowRepresentable(RowViewType.TITLE_VALUE, resId = R.string.net_result, computedStat = netComputedStat))
		rows.add(CustomizableRowRepresentable(RowViewType.TITLE_VALUE, resId = R.string.net_banked, computedStat = netBankedComputedStat))

		if (bankrollReport.transactionBuckets.isNotEmpty()) {
			rows.add(CustomizableRowRepresentable(RowViewType.HEADER_TITLE, resId = R.string.operations))
			bankrollReport.transactionBuckets.keys.forEach { key ->
				bankrollReport.transactionBuckets[key]?.let { transactionBucket ->
					val typeName = transactionBucket.transactions.firstOrNull()?.type?.getDisplayName(requireContext())
					val computedStat = ComputedStat(Stat.NET_RESULT, transactionBucket.total)
					rows.add(CustomizableRowRepresentable(RowViewType.TITLE_VALUE, title = typeName, computedStat = computedStat))
				}
			}
		}

	}

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

		setDisplayHomeAsUpEnabled(true)

		updateMenuUI()

		bankrollAdapter = RowRepresentableAdapter(this, this)

		val viewManager = LinearLayoutManager(requireContext())

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

	/**
	 * Update menu UI
	 */
	private fun updateMenuUI() {

		if (bankrollReport.setup.virtualBankroll) {
			setToolbarTitle(getString(R.string.total))
			bankrollDetailsMenu?.findItem(R.id.settings)?.isVisible = false
		} else {
			setToolbarTitle(bankrollReport.setup.bankroll?.name)
			bankrollDetailsMenu?.findItem(R.id.settings)?.isVisible = true
		}

	}

	/**
	 * Open Bankroll edit activity
	 */
	private fun editBankroll() {
		EditableDataActivity.newInstanceForResult(this, LiveData.BANKROLL, bankrollReport.setup.bankroll?.id, REQUEST_CODE_EDIT)
	}

}