package net.pokeranalytics.android.ui.fragment.components

import android.os.Bundle
import android.view.View
import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.Fragment
import com.crashlytics.android.Crashlytics
import net.pokeranalytics.android.R
import net.pokeranalytics.android.ui.activity.components.PokerAnalyticsActivity

open class PokerAnalyticsFragment : Fragment() {

	private var loaderDialogFragment: LoaderDialogFragment? = null
	var parentActivity: PokerAnalyticsActivity? = null

	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		Crashlytics.log("$this.localClassName onCreate")
	}

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

	override fun onResume() {
		super.onResume()
		Crashlytics.log("$this.localClassName onResume")
	}

	override fun onPause() {
		super.onPause()
		Crashlytics.log("$this.localClassName onPause")
	}

	override fun onDestroy() {
		super.onDestroy()
		Crashlytics.log("$this.localClassName onDestroy")
	}

	/**
	 * Method called when the activity override onBackPressed and send the information to the fragment
	 */
	open fun onBackPressed() {}

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

		setHasOptionsMenu(true)

		parentActivity = activity as PokerAnalyticsActivity

		// Set the toolbar to the parent activity

		view?.findViewById<Toolbar>(R.id.toolbar)?.let { toolbar ->
			parentActivity?.setSupportActionBar(toolbar)
		}
	}

	/**
	 * Show the loader
	 */
	fun showLoader(resId: Int? = null, cancelable: Boolean = false) {
		loaderDialogFragment = LoaderDialogFragment.newInstance(resId, cancelable)
		activity?.let {
			loaderDialogFragment?.show(it.supportFragmentManager, "loader")
		}
	}

	/**
	 * Hide the loader
	 */
	fun hideLoader() {
		loaderDialogFragment?.dismiss()
		loaderDialogFragment = null
	}

	/**
	 * Set the toolbar title
	 */
	fun setToolbarTitle(title: String?) {
		view?.findViewById<Toolbar>(R.id.toolbar)?.let { toolbar ->
			toolbar.title = title
		}
		parentActivity?.supportActionBar?.title = title
	}

	/**
	 * Display or not the back arrow icon
	 */
	fun setDisplayHomeAsUpEnabled(enabled: Boolean) {
		parentActivity?.supportActionBar?.setDisplayHomeAsUpEnabled(enabled)
	}

}