package com.ersen.viewpager2fragmenubug

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter

class ViewPager2FragmentAdapter : FragmentStateAdapter {

    constructor(fragment: Fragment) : super(fragment)

    constructor(fragmentActivity: FragmentActivity) : super(fragmentActivity)

    private var mItems = listOf<Item>()

    override fun getItemCount(): Int = mItems.size

    override fun createFragment(position: Int): Fragment = mItems[position].fragmentProvider.invoke()

    override fun getItemId(position: Int): Long = mItems[position].id

    override fun containsItem(itemId: Long): Boolean {
        return mItems.firstOrNull { it.id == itemId } != null
    }

    fun setItems(items: List<Item>) {
        mItems = items
        notifyDataSetChanged()
    }

    fun getPositionFromId(id: Long): Int {
        mItems.indexOfFirst { it.id == id }.let {
            return if (it == -1) {
                0
            } else {
                it
            }
        }
    }

    class Item(val id: Long, val fragmentProvider: () -> Fragment)

}