package net.pokeranalytics.android.ui.fragment

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.github.mikephil.charting.data.Entry
import kotlinx.android.synthetic.main.fragment_statistic_details.*
import net.pokeranalytics.android.R
import net.pokeranalytics.android.calculus.Stat
import net.pokeranalytics.android.ui.activity.StatisticDetailsActivity
import net.pokeranalytics.android.ui.activity.components.PokerAnalyticsActivity
import net.pokeranalytics.android.ui.fragment.components.PokerAnalyticsFragment

class StatisticDetailsFragment : PokerAnalyticsFragment() {

	companion object {
		fun newInstance(context: Context) {
			val intent = Intent(context, StatisticDetailsFragment::class.java)
			context.startActivity(intent)
		}
	}

	private lateinit var parentActivity: PokerAnalyticsActivity

	private var stat: Stat = Stat.NETRESULT
	private var entries: List<Entry> = ArrayList()

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

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

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

		parentActivity = activity as PokerAnalyticsActivity

		// Avoid a bug during setting the title
		toolbar.title = ""

		parentActivity.setSupportActionBar(toolbar)
		parentActivity.supportActionBar?.setDisplayHomeAsUpEnabled(true)
		setHasOptionsMenu(true)

		toolbar.title = stat.localizedTitle(requireContext())

		val fragmentManager = parentActivity.supportFragmentManager
		val fragmentTransaction = fragmentManager.beginTransaction()
		val fragment = GraphFragment()

		fragmentTransaction.add(R.id.container, fragment)
		fragmentTransaction.commit()

		StatisticDetailsActivity.parameters?.let {
			fragment.setData(it.stat, it.computableGroup, it.report)
			StatisticDetailsActivity.parameters = null
		} ?: run {
			throw Exception("Missing graph parameters")
		}
	}

	/**
	 * Set data
	 */
	fun setData(stat: Stat, entries: List<Entry>) {
		this.stat = stat
		this.entries = entries
	}

}