package net.pokeranalytics.android.ui.adapter

import android.util.SparseArray
import android.view.ViewGroup
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import net.pokeranalytics.android.ui.fragment.*
import net.pokeranalytics.android.ui.fragment.components.PokerAnalyticsFragment
import java.lang.ref.WeakReference

/**
 * Home Adapter
 */
class HomePagerAdapter(fragmentManager: FragmentManager) : FragmentStatePagerAdapter(fragmentManager) {

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

	override fun getItem(position: Int): PokerAnalyticsFragment {
		return when (position) {
			0 -> FeedFragment.newInstance()
			1 -> StatisticsFragment.newInstance()
			2 -> CalendarFragment.newInstance()
			3 -> ReportsFragment.newInstance()
			4 -> MoreFragment.newInstance()
			else -> FeedFragment.newInstance()
		}
	}

	override fun getCount(): Int {
		return 5
	}

	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 when (obj) {
			FeedFragment::class.java -> 0
			StatisticsFragment::class.java -> 1
			CalendarFragment::class.java -> 2
			ReportsFragment::class.java -> 3
			SettingsFragment::class.java -> 4
			else -> -1
		}
	}

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

}