package com.adealink.weparty.commonui.widget.tablayout

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.viewpager2.widget.ViewPager2
import com.adealink.frame.log.Log
import com.adealink.frame.mvvm.viewmodel.BaseViewModel
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import java.lang.ref.WeakReference

/**
 * [TabLayoutMediator]
 */
class TabLayoutMediatorViewModel : BaseViewModel(), ITabLayoutMediatorViewModel {
    override val viewPagerLD: LiveData<ViewPager2> = MutableLiveData()
    private var tabNameList = listOf<String>()

    private var tabLayoutRef: WeakReference<TabLayout>? = null
    private var tabConfigurationStrategy: TabLayoutMediator.TabConfigurationStrategy? = null
    private var viewPagerRef: WeakReference<ViewPager2>? = null

    private var mediator: TabLayoutMediator? = null

    override fun setTabLayout(tabLayout: TabLayout, tabConfigurationStrategy: TabLayoutMediator.TabConfigurationStrategy) {
        tabLayoutRef = WeakReference(tabLayout)
        this.tabConfigurationStrategy = tabConfigurationStrategy
        tryReAttach()
    }

    override fun setViewPager(viewPager: ViewPager2) {
        viewPagerRef = WeakReference(viewPager)
        viewPagerLD.send(viewPager)
        tryReAttach()
    }

    override fun setTabNameList(list: List<String>) {
        this.tabNameList = list
    }

    override fun getTabNameBy(position: Int): String? {
        return tabNameList.getOrNull(position)
    }

    private fun tryReAttach() {
        //解绑之前关系
        mediator?.detach()
        mediator = null

        //创建新的绑定关系
        val tabLayout = this.tabLayoutRef?.get()
        val tabStrategy = tabConfigurationStrategy
        if (tabLayout == null || tabStrategy == null) {
            Log.d(TAG, "tryReAttach return, for tabLayout($tabLayout) or tabStrategy($tabStrategy) is null")
            return
        }
        val viewPager = this.viewPagerRef?.get()
        if (viewPager == null) {
            Log.d(TAG, "tryReAttach return, for viewPager($viewPager) is null")
            return
        }
        mediator = TabLayoutMediator(tabLayout, viewPager, true,false,tabStrategy).also { it.attach() }
    }


    companion object {
        const val TAG = "TabLayoutMediatorViewModel"
    }

}