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.recyclerview.widget.LinearLayoutManager
import io.realm.RealmResults
import kotlinx.android.synthetic.main.fragment_history.*
import net.pokeranalytics.android.R
import net.pokeranalytics.android.model.realm.Session
import net.pokeranalytics.android.ui.activity.SessionActivity
import net.pokeranalytics.android.ui.adapter.HistoryAdapter
import net.pokeranalytics.android.ui.fragment.components.PokerAnalyticsFragment
import net.pokeranalytics.android.util.data.sessionDao

class HistoryFragment : PokerAnalyticsFragment() {

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

	private lateinit var historyAdapter: HistoryAdapter
	private var realmSessions: RealmResults<Session>? = null

	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() {

		newSession.setOnClickListener {
			SessionActivity.newInstance(requireContext(), false)
		}

		newTournament.setOnClickListener {
			SessionActivity.newInstance(requireContext(), true)
		}

		newHand.setOnClickListener {
			Toast.makeText(requireContext(), "Open new hand", Toast.LENGTH_SHORT).show()
		}
		newTransaction.setOnClickListener {
			Toast.makeText(requireContext(), "Open new transaction", Toast.LENGTH_SHORT).show()
		}

	}

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

		realmSessions = getRealm().sessionDao().findAllSessions()
		realmSessions?.let {

			val viewManager = LinearLayoutManager(requireContext())
			historyAdapter = HistoryAdapter(it)

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

			historyAdapter.onClickOnSession = {position, session ->
				SessionActivity.newInstance(requireContext(), sessionId = session.id)
			}

			it.addChangeListener { newSessions ->
				historyAdapter.notifyDataSetChanged()
			}
		}

	}

}