package com.sunny.app.soft.timberkeyboardnew.ui.activity

import android.view.View
import android.view.ViewParent
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.sunny.app.soft.timberkeyboardnew.R
import com.sunny.app.soft.timberkeyboardnew.databinding.ActivityMainBinding
import com.sunny.app.soft.timberkeyboardnew.ui.adapter.MainViewPagerAdapter
import com.sunny.app.soft.timberkeyboardnew.ui.fragment.HomeFragment
import com.sunny.app.soft.timberkeyboardnew.ui.fragment.SettingFragment

class MainActivity :
    BaseActivity(),
    View.OnClickListener,
    ViewPager.OnPageChangeListener {

    private lateinit var binding: ActivityMainBinding
    private lateinit var fragmentList: MutableList<Fragment>

    override fun setRootView(): View {
        binding = ActivityMainBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initView() {
        super.initView()
        initViewPager()
        initTabButton()
    }

    private fun initTabButton() {
        binding.mainTabHome.setOnClickListener(this)
        binding.mainTabSet.setOnClickListener(this)
    }

    private fun initViewPager() {
        fragmentList = mutableListOf()
        fragmentList.add(HomeFragment())
        fragmentList.add(SettingFragment())
        binding.mainViewpager.apply {
            adapter = MainViewPagerAdapter(fragmentList, supportFragmentManager)
            addOnPageChangeListener(this@MainActivity)
            offscreenPageLimit = 0
            setTabSelect(0)
        }
    }

    private fun setTabSelect(i: Int) {
        when (i) {
            0 -> {
                binding.mainTabHome.isSelected = true
                binding.mainTabSet.isSelected = false
                binding.mainTvHome.setTextColor(getColor(R.color.orange))
                binding.mainTvSetting.setTextColor(getColor(R.color.black))
                binding.mainViewpager.currentItem = 0
            }

            1 -> {
                binding.mainTabHome.isSelected = false
                binding.mainTabSet.isSelected = true
                binding.mainTvHome.setTextColor(getColor(R.color.black))
                binding.mainTvSetting.setTextColor(getColor(R.color.orange))
                binding.mainViewpager.currentItem = 1
            }
        }
    }

    override fun onClick(v: View?) {
        when (v) {
            binding.mainTabHome -> {
                setTabSelect(0)
            }

            binding.mainTabSet -> {
                setTabSelect(1)
            }
        }
    }

    override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
    }

    override fun onPageSelected(position: Int) {
        setTabSelect(position)
    }

    override fun onPageScrollStateChanged(state: Int) {
    }

}