package com.seatel.mobilehall.ui.usage.adapter

import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import com.seatel.mobilehall.ui.base.fragment.BaseFragment
import com.seatel.mobilehall.util.AnalyticsHelper

class UsageAdapter(fragmentManager: FragmentManager) : FragmentPagerAdapter(fragmentManager) {

    private val fragments = LinkedHashMap<BaseFragment, String>()
    private var mCurrentFragment: BaseFragment? = null

    override fun getItem(position: Int): Fragment {
        return fragments.keys.elementAt(position)
    }

    private fun getCurrentFragment(): BaseFragment? {
        return mCurrentFragment
    }

    override fun setPrimaryItem(container: ViewGroup, position: Int, `object`: Any) {
        super.setPrimaryItem(container, position, `object`)

        if (getCurrentFragment() !== `object`) {
            mCurrentFragment = `object` as BaseFragment
        }
    }

    override fun getCount(): Int {
        return fragments.keys.size
    }

    fun addFragment(fragment: BaseFragment, title: String) {
        AnalyticsHelper.logEvent(AnalyticsHelper.Event.USAGE_TAP + "$title", null)
        fragments[fragment] = title
    }

    override fun getPageTitle(position: Int): CharSequence {
        return fragments.values.elementAt(position)
    }
}