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 net.pokeranalytics.android.R
import net.pokeranalytics.android.ui.fragment.CalendarFragment
import net.pokeranalytics.android.ui.fragment.GraphFragment
import net.pokeranalytics.android.ui.fragment.FeedFragment
import net.pokeranalytics.android.ui.fragment.components.PokerAnalyticsFragment
import java.lang.ref.WeakReference

/**
 * Comparison Chart Pager Adapter
 */
class ComparisonChartPagerAdapter(val context: Context, fragmentManager: FragmentManager) : FragmentStatePagerAdapter(fragmentManager) {

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

	override fun getItem(position: Int): PokerAnalyticsFragment {
		return when (position) {
			0 -> GraphFragment()
			1 -> GraphFragment()
			2 -> CalendarFragment.newInstance()
			else -> FeedFragment.newInstance()
		}
	}

	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.data_table)
			else -> super.getPageTitle(position)
		}
	}

	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 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
	}

}