package com.ama.core.architecture.util

import androidx.viewpager2.widget.ViewPager2
import com.ama.core.architecture.base.views.adapter.BaseFragmentStateAdapter
import com.ama.core.common.util.asUnsafe
import com.ama.core.model.BaseFragmentStateDiffItem
import kotlin.collections.isNullOrEmpty




fun <T : BaseFragmentStateDiffItem> ViewPager2.setDataOrAdapter(
    dataList: List<T>?,
    offscreenPageLimit: Int?,
    createAdapter: () -> BaseFragmentStateAdapter<T>,
) {
    setOffscreenPageLimit(
        if (offscreenPageLimit == null || offscreenPageLimit <= 0) {
            // 小值，用默认的。
            ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT
        } else if (offscreenPageLimit == Int.MAX_VALUE) {
            // 大值，用全部的。
            val itemCount = (dataList?.size ?: 0)
            if (itemCount >= 2) {
                // 2个及以上
                itemCount - 1
            } else {
                // 没有或者仅有1个，用默认的
                ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT
            }
        } else {
            // 中间值，用设置的值。
            offscreenPageLimit
        }
    )

    if (adapter == null) {
        if (dataList.isNullOrEmpty()) return
        val fragmentStateAdapter = createAdapter()
        fragmentStateAdapter.submitList(dataList)

        adapter = fragmentStateAdapter
    } else {
        // update adapter
        adapter.asUnsafe<BaseFragmentStateAdapter<T>>().submitList(dataList)
    }
}