package com.yidian.yac.newscontent.ui

import android.os.Bundle
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import com.yidian.common.base.BaseFragment
import com.yidian.yac.newscontent.R
import kotlinx.android.synthetic.main.fragment_explore.*

class ExploreFragment:BaseFragment() {
    companion object{
        fun newInstance():ExploreFragment{
            val fragment = ExploreFragment()
            val args = bundleOf()
            fragment.arguments = args
            return fragment
        }
    }
    override val contentViewId: Int
        get() = R.layout.fragment_explore
    private lateinit var tabs:ArrayList<String>
    private lateinit var fragments:ArrayList<AChannelFragment>
    private lateinit var fragmentAdapter:ExploreFragmentPagerAdapter
    override fun init(savedInstanceState: Bundle?) {
        super.init(savedInstanceState)
        initView()
    }

    private fun initView() {
        initViewData()
        fragmentAdapter = ExploreFragmentPagerAdapter(childFragmentManager,FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT)
        fragmentAdapter.setFragments(fragments)
        vp_explore.adapter = fragmentAdapter
        tl_explore.setupWithViewPager(vp_explore,false)
    }

    private fun initViewData() {
        tabs = arrayListOf("热门","财经","娱乐","体育","搞笑","军事")
        fragments = ArrayList<AChannelFragment>()
        tabs.forEach {
            tl_explore.addTab(tl_explore.newTab().setText(it))
            val fragment = ChannelFragment.newInstance(it)
            fragment.channelName = it
            fragments.add(fragment)
        }
    }
}
class ExploreFragmentPagerAdapter(fragmentManager: FragmentManager, behavior:Int):
    FragmentPagerAdapter(fragmentManager,behavior){
   private val fragments = ArrayList<AChannelFragment>()

    override fun getItem(position: Int): Fragment {
        return fragments[position]
    }

    override fun getCount(): Int {
        return fragments.size
    }

    override fun getPageTitle(position: Int): CharSequence? {
        return fragments[position].channelName
    }
    fun setFragments(list:ArrayList<AChannelFragment>){
        fragments.clear()
        fragments.addAll(list)
    }
}