package com.yidian.yac.newscontent.ui

import android.os.Bundle
import android.widget.TextView
import androidx.core.os.bundleOf
import com.yidian.common.base.BaseFragment
import com.yidian.yac.newscontent.R
import kotlinx.android.synthetic.main.fragment_home.*

class HomeFragment:BaseFragment() {
    companion object{
        fun newInstance():HomeFragment{
            val fragment = HomeFragment()
            val args = bundleOf()
            fragment.arguments = args
            return fragment
        }
    }
    override val contentViewId: Int
        get() = R.layout.fragment_home
    private val subscriptionFragment:BaseFragment by lazy { SubscriptionFragment.newInstance() }
    private val newsFlashFragment:BaseFragment by lazy { NewsFlashFragment.newInstance() }
    private lateinit var selectedTv:TextView
    private lateinit var selectedFragment:BaseFragment
    override fun init(savedInstanceState: Bundle?) {
        super.init(savedInstanceState)
        initView()
        initFragment()
        initListener()
    }

    private fun initListener() {
      tv_subscription.setOnClickListener {
          switchSelected(tv_subscription)
          switchFragment(subscriptionFragment)
      }
      tv_newsFlash.setOnClickListener {
          switchSelected(tv_newsFlash)
          switchFragment(newsFlashFragment)
      }
    }

    private fun initView() {
        selectedTv=tv_subscription
        switchSelected(tv_subscription)
    }

    private fun switchSelected(selectedTv: TextView) {
        if (selectedTv == this.selectedTv ) return
        this.selectedTv.textSize = 14f
        this.selectedTv.setTextColor(resources.getColor(R.color.homeGray))
        selectedTv.textSize = 16f
        selectedTv.setTextColor(resources.getColor(R.color.colorPrimaryDark))
        this.selectedTv = selectedTv
    }
    private fun switchFragment(fragment:BaseFragment){
        if (fragment == selectedFragment) return
        val transaction = childFragmentManager.beginTransaction()
        childFragmentManager.fragments.forEach {
            transaction.hide(it)
        }
        if (fragment.isAdded){
            transaction.show(fragment)
        }else{
            transaction.add(R.id.fragment_container,fragment)
        }
        transaction.commitAllowingStateLoss()
        selectedFragment = fragment
    }
    private fun initFragment() {
        val transaction = childFragmentManager.beginTransaction()
        transaction.add(R.id.fragment_container,subscriptionFragment)
        transaction.commitAllowingStateLoss()
        selectedFragment = subscriptionFragment
    }


}