package net.pokeranalytics.android.ui.adapter

import android.content.Context
import android.util.SparseArray
import android.view.ViewGroup
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.viewpager.widget.PagerAdapter
import net.pokeranalytics.android.R
import net.pokeranalytics.android.calculus.Report
import net.pokeranalytics.android.ui.fragment.GraphFragment
import net.pokeranalytics.android.ui.fragment.report.ComposableTableReportFragment
import net.pokeranalytics.android.ui.fragment.components.PokerAnalyticsFragment
import java.lang.ref.WeakReference

/**
 * Home Adapter
 */
class ReportPagerAdapter(val context: Context, val fragmentManager: FragmentManager, private val report: Report) : FragmentStatePagerAdapter(fragmentManager) {

	var weakReferences = SparseArray<WeakReference<PokerAnalyticsFragment>>()

	override fun getItem(position: Int): PokerAnalyticsFragment {
		return when (position) {
			0 -> {
				val dataSetList = listOf(report.barEntries(null, context))
				GraphFragment.newInstance(barDataSets = dataSetList, style = GraphFragment.Style.BAR)
			}
			1 -> {
				val dataSetList = report.multiLineEntries(context = context)
				GraphFragment.newInstance(lineDataSets = dataSetList, style = GraphFragment.Style.MULTILINE)
			}
			2 -> {
				ComposableTableReportFragment.newInstance(report)
			}
			else -> PokerAnalyticsFragment()
		}
	}

	override fun getCount(): Int {
		return 3
	}

	override fun getPageTitle(position: Int): CharSequence? {
		return when(position) {
			0 -> context.getString(R.string.bars)
			1 -> context.getString(R.string.lines)
			2 -> context.getString(R.string.table)
			else -> ""
		}
	}

	override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
		super.destroyItem(container, position, `object`)
		weakReferences.remove(position)
	}

	override fun instantiateItem(container: ViewGroup, position: Int): Any {
		val fragment = super.instantiateItem(container, position) as PokerAnalyticsFragment
		weakReferences.put(position, WeakReference(fragment))
		return fragment
	}

	override fun getItemPosition(obj: Any): Int {
		return PagerAdapter.POSITION_UNCHANGED
	}

	/**
	 * Return the fragment at the position key
	 */
	fun getFragment(key: Int): PokerAnalyticsFragment? {
		if (weakReferences.get(key) != null) {
			return weakReferences.get(key).get()
		}
		return null
	}

}