package net.pokeranalytics.android.ui.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.view.isVisible
import androidx.interpolator.view.animation.FastOutSlowInInterpolator
import io.realm.RealmResults
import io.realm.Sort
import io.realm.kotlin.where
import kotlinx.android.synthetic.main.fragment_history.*
import net.pokeranalytics.android.R
import net.pokeranalytics.android.model.interfaces.Editable
import net.pokeranalytics.android.model.realm.Session
import net.pokeranalytics.android.ui.activity.SessionActivity
import net.pokeranalytics.android.ui.adapter.HistorySessionRowRepresentableAdapter
import net.pokeranalytics.android.ui.adapter.LiveRowRepresentableDataSource
import net.pokeranalytics.android.ui.adapter.RowRepresentableDelegate
import net.pokeranalytics.android.ui.fragment.components.PokerAnalyticsFragment
import net.pokeranalytics.android.ui.view.RowRepresentable
import net.pokeranalytics.android.ui.view.SmoothScrollLinearLayoutManager
import net.pokeranalytics.android.util.Preferences
import java.text.SimpleDateFormat
import java.util.*

class HistoryFragment : PokerAnalyticsFragment(), LiveRowRepresentableDataSource, RowRepresentableDelegate {

	companion object {
		fun newInstance(): HistoryFragment {
			val fragment = HistoryFragment()
			val bundle = Bundle()
			fragment.arguments = bundle
			return fragment
		}
	}

	private lateinit var historyAdapter: HistorySessionRowRepresentableAdapter

	private lateinit var realmSessions: RealmResults<Session>
	private val rows: ArrayList<RowRepresentable> = ArrayList()
	private var newSessionCreated: Boolean = false

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

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

	override fun onDestroyView() {
		super.onDestroyView()
		realmSessions.removeAllChangeListeners()
	}

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

		disclaimerContainer.isVisible = Preferences.shouldShowDisclaimer(requireContext())

		val sdf = SimpleDateFormat("dd/M/yyyy hh:mm")
		val betaLimitDate = sdf.parse("17/7/2019 10:00")

		newCashGame.setOnClickListener {

			if (Date().after(betaLimitDate)) {
				this.showEndOfBetaMessage()
				return@setOnClickListener
			}

			SessionActivity.newInstance(requireContext(), false)
			newSessionCreated = true
		}

		newTournament.setOnClickListener {

			if (Date().after(betaLimitDate)) {
				this.showEndOfBetaMessage()
				return@setOnClickListener
			}

			SessionActivity.newInstance(requireContext(), true)
			newSessionCreated = true
		}

		disclaimerDismiss.setOnClickListener {
			Preferences.setStopShowingDisclaimer(requireContext())

			disclaimerContainer.animate().translationY(disclaimerContainer.height.toFloat())
				.setInterpolator(FastOutSlowInInterpolator())
				.withEndAction { disclaimerContainer?.isVisible = false }
				.start()
		}

	}

	private fun showEndOfBetaMessage() {
		Toast.makeText(context, "Beta has ended. Please update with the Google Play version", Toast.LENGTH_LONG).show()

	}

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

		this.realmSessions = getRealm().where<Session>().findAll().sort("startDate", Sort.DESCENDING)
		this.realmSessions.addChangeListener { _, changeSet ->
			this.historyAdapter.refreshData()
			this.historyAdapter.notifyDataSetChanged()
		}

		val startedSessions = getRealm().where<Session>().isNotNull("year").isNotNull("month").findAll().sort("startDate", Sort.DESCENDING)
		val pendingSessions = getRealm().where<Session>().isNull("year").isNull("month").findAll().sort("startDate", Sort.DESCENDING)
		val distinctDateSessions = getRealm().where<Session>().distinct("year", "month").findAll().sort("startDate", Sort.DESCENDING)

		this.historyAdapter = HistorySessionRowRepresentableAdapter(this, startedSessions, pendingSessions, distinctDateSessions)

		val viewManager = SmoothScrollLinearLayoutManager(requireContext())
		recyclerView.apply {
			setHasFixedSize(true)
			layoutManager = viewManager
			adapter = historyAdapter
		}
	}

	override fun rowRepresentableForPosition(position: Int): RowRepresentable? {
		return this.rows[position]
	}

	override fun numberOfRows(): Int {
		return this.rows.size
	}

	override fun viewTypeForPosition(position: Int): Int {
		return rows[position].viewType
	}

	override fun indexForRow(row: RowRepresentable): Int {
		return this.rows.indexOf(row)
	}

	override fun onRowSelected(position: Int, row: RowRepresentable, fromAction: Boolean) {
		SessionActivity.newInstance(requireContext(), sessionId = (row as Editable).id)
	}
}