package com.gh.gamecenter.servers

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.CheckedTextView
import android.widget.RelativeLayout
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.viewpager.widget.ViewPager
import com.gh.base.DownloadToolbarActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.adapter.FragmentAdapter
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.constant.EntranceConsts.KEY_LAST_SELECTED_POSITION
import com.gh.gamecenter.common.utils.updateStatusBarColor
import com.gh.gamecenter.common.utils.viewModelProviderFromParent
import com.gh.gamecenter.common.view.DrawableView
import com.gh.gamecenter.core.runOnIoThread
import com.gh.gamecenter.core.utils.MtaHelper
import com.halo.assistant.HaloApp
import com.lightgame.view.NoScrollableViewPager

class GameServersActivity : DownloadToolbarActivity() {

    private var mServersTest: CheckedTextView? = null
    private var mServersPublish: CheckedTextView? = null
    private var mViewpager: NoScrollableViewPager? = null
    private var mTabIndicatorView: View? = null
    private var mTabContainer: View? = null
    private var mFakeToolbarTitleTv: View? = null

    private lateinit var mIndicatorParams: RelativeLayout.LayoutParams

    private val mFragments = ArrayList<Fragment>()

    private val mServersTestIndex = 1
    private val mServersPublishIndex = 0

    private var mViewModel: GameServersTestViewModel? = null

    override fun getLayoutId(): Int {
        return R.layout.activity_game_servers
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        updateStatusBarColor(R.color.background_white, R.color.background_white)
        mServersTest = findViewById(R.id.server_test)
        mServersPublish = findViewById(R.id.server_publish)
        mViewpager = findViewById(R.id.viewpager)
        mTabIndicatorView = findViewById(R.id.tab_indicator)
        mTabContainer = findViewById(R.id.tab_container)
        mFakeToolbarTitleTv = findViewById(R.id.toolbarTitleTv)

        savedInstanceState?.run {
            if (getInt(KEY_LAST_SELECTED_POSITION) == 1) {
                mTabContainer?.post {
                    updateIndicatorOffset(0.999F)
                }
            }
        }
        setToolbarMenu(R.menu.menu_download)

        mViewModel = viewModelProviderFromParent(GameServersTestViewModel.Factory(HaloApp.getInstance(), "general"))
        mViewModel?.load()
        mViewModel?.isTestOnLiveData?.observe(this, Observer {
            if (it) {
                mViewpager?.setScrollable(true)
                mFakeToolbarTitleTv?.visibility = View.GONE
            } else {
                mViewpager?.setScrollable(false)
            }
        })

        mToolbar.setNavigationOnClickListener { finish() }
        mServersPublish?.isChecked = true
        mServersTest?.setTextColor(DrawableView.getSelectorColorStyle(R.color.text_black, R.color.theme_font, this))
        mServersPublish?.setTextColor(DrawableView.getSelectorColorStyle(R.color.text_black, R.color.theme_font, this))
        mServersTest?.setOnClickListener { mViewpager?.currentItem = mServersTestIndex }
        mServersPublish?.setOnClickListener { mViewpager?.currentItem = mServersPublishIndex }

        mIndicatorParams = mTabIndicatorView?.layoutParams as RelativeLayout.LayoutParams

        val mtaTabSelectedClosure =
            { MtaHelper.onEvent("开服表", "Tab", if (mServersTest?.isChecked == true) "开测" else "开服") }
        // init viewpager
        mFragments.add(GameServersPublishFragment())
        mFragments.add(GameServersTestFragment())
        mViewpager?.setScrollable(false)
        mViewpager?.offscreenPageLimit = 1
        mViewpager?.adapter = FragmentAdapter(supportFragmentManager, mFragments)
        mViewpager?.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
                updateIndicatorOffset(positionOffset)
            }

            override fun onPageSelected(position: Int) {
                mServersTest?.isChecked = position == mServersTestIndex
                mServersPublish?.isChecked = mServersTest?.isChecked != true
                mtaTabSelectedClosure()
            }

            override fun onPageScrollStateChanged(state: Int) {
                setPageScrollState(state)
            }
        })
        mtaTabSelectedClosure()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        outState.putInt(KEY_LAST_SELECTED_POSITION, mViewpager?.currentItem ?: 0)
        super.onSaveInstanceState(outState)
    }

    private fun updateIndicatorOffset(positionOffset: Float) {
        if (mServersTest == null || mTabIndicatorView == null || mTabContainer == null) return
        val indicatorMargin = mServersTest!!.width - (mTabIndicatorView!!.width)
        val leftOffset = indicatorMargin / 2
        val width = mTabContainer!!.width - mTabIndicatorView!!.width - indicatorMargin
        if (width > 0 && positionOffset > 0 && positionOffset < 1) {
            mIndicatorParams.leftMargin = (width.toFloat() * positionOffset).toInt() + leftOffset
            mTabIndicatorView!!.layoutParams = mIndicatorParams
        }
    }

    private fun setPageScrollState(state: Int) {
        runOnIoThread {
            for (fragment in mFragments) {
                if (fragment.userVisibleHint && fragment.host != null) {
                    val fragments = fragment.childFragmentManager.fragments
                    for (childFragment in fragments) {
                        if (childFragment is GameServersContentFragment) {
                            childFragment.vpScrollState(state)
                        } else if (childFragment is GameServersTestFragment) {
                            childFragment.vpScrollState(state)
                        }
                    }
                }
            }
        }
    }

    override fun showDownloadMenu(): Boolean {
        return true
    }

    override fun getActivityNameInChinese(): String {
        return "开服表"
    }

    override fun isAutoResetViewBackgroundEnabled() = true

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        updateStatusBarColor(R.color.background_white, R.color.background_white)
        mServersTest?.setTextColor(DrawableView.getSelectorColorStyle(R.color.text_black, R.color.theme_font, this))
        mServersPublish?.setTextColor(DrawableView.getSelectorColorStyle(R.color.text_black, R.color.theme_font, this))
    }

    companion object {
        @JvmStatic
        fun getIntent(context: Context, entrance: String, path: String): Intent {
            val intent = Intent(context, GameServersActivity::class.java)
            intent.putExtra(EntranceConsts.KEY_ENTRANCE, mergeEntranceAndPath(entrance, path))
            return intent
        }
    }
}