package com.keyboard.themes.key.fagment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager.widget.ViewPager
import com.keyboard.themes.key.AppThemes
import com.keyboard.themes.key.daapter.AdapterTabName
import com.keyboard.themes.key.data.Parent
import com.keyboard.themes.key.databinding.ThemeLayoutThemeFragmentBinding

class FragMain : Fragment() {


    private lateinit var vb: ThemeLayoutThemeFragmentBinding


    private lateinit var viewContent: ViewPager
    lateinit var viewAllList: MutableList<Parent>
    private lateinit var adapterTabName: AdapterTabName



    companion object {

        @JvmStatic
        fun newInstance() =
            FragMain()
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        vb = ThemeLayoutThemeFragmentBinding.inflate(layoutInflater)
        viewContent = vb.viewPager
        setTabRecycler()
        setContent()
        return vb.root
    }


    private fun setTabRecycler() {
        viewAllList = AppThemes.list
        adapterTabName = AdapterTabName(
            requireContext()
        ).apply {
            tabTitleName(viewAllList)
            setChangeListener { posit -> viewContent.setCurrentItem(posit, false) }
        }
        vb.tabRecycler.run {
            adapter = adapterTabName
            layoutManager = LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
        }
    }

    private fun setContent() {
        val fragList = mutableListOf<Fragment>()
        for (index in 0 until viewAllList.size) {
            fragList.add(FragThemes.newInstance(index))
        }

        viewContent.adapter = object : FragmentStatePagerAdapter(
            childFragmentManager,
            BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
        ) {
            override fun getCount(): Int = fragList.size

            override fun getItem(position: Int): Fragment = fragList[position]

        }
        var curViewPager = 0
        viewContent.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
                if (curViewPager != position) {
                    adapterTabName.setSelectedPos(position)
//                    tabRecycler.scrollToPosition(position)
                    curViewPager = position
                }

            }

            override fun onPageSelected(position: Int) {

            }

            override fun onPageScrollStateChanged(state: Int) {

            }

        })
    }


}