package com.adealink.weparty.commonui.viewpager

import android.annotation.SuppressLint
import android.util.SparseArray
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter

data class Tab(val titleResId: Int, val instance: () -> Fragment)

class TabsPagerAdapter : FragmentStateAdapter {

    private var tabs: List<Tab> = arrayListOf()
    private val fragments = SparseArray<Fragment>()

    constructor(fragment: Fragment) : super(fragment)

    constructor(fragment: Fragment, tabs: List<Tab>) : super(fragment) {
        this.tabs = tabs
    }

    constructor(fragmentActivity: FragmentActivity, tabs: List<Tab>) : super(fragmentActivity) {
        this.tabs = tabs
    }

    @SuppressLint("NotifyDataSetChanged")
    fun update(tabs: List<Tab>) {
        this.tabs = tabs
        this.fragments.clear()
        notifyDataSetChanged()
    }

    override fun getItemId(position: Int): Long {
        return tabs[position].titleResId.toLong()
    }

    override fun containsItem(itemId: Long): Boolean {
        val tab = tabs.find { it.titleResId.toLong() == itemId }
        return tab != null
    }

    override fun getItemCount(): Int {
        return tabs.size
    }

    override fun createFragment(position: Int): Fragment {
        return tabs[position].let { it.instance() }.apply { fragments.put(position, this) }
    }

    fun <T : Fragment> getFragment(position: Int, clazz: Class<T>): T? {
        val fragment = fragments[position]
        return if (clazz.isInstance(fragment)) {
            clazz.cast(fragment)
        } else {
            null
        }
    }

    @Deprecated("还是可能抛出ClassCastException，使用getFragment(position: Int, clazz: Class<T>)替代")
    fun <T : Fragment> getFragment(position: Int): T? {
        return fragments[position] as? T
    }

    fun getTab(position: Int): Tab {
        return tabs[position]
    }

}