package com.gh.gamecenter.wrapper

import android.annotation.SuppressLint
import android.app.Application
import androidx.lifecycle.*
import com.gh.common.util.ViewPagerFragmentHelper
import com.gh.gamecenter.common.utils.singleToMain
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.entity.MultiTabNav
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

open class TabWrapperViewModel(
    application: Application,
    private val mMultiTabNavId: String,
    internal val repository: MainWrapperRepository
) : AndroidViewModel(application) {
    private val mNewApi = RetrofitManager.getInstance().newApi

    var defaultTabPosition = 0

    val tabListLiveData = MutableLiveData<List<MultiTabNav.LinkMultiTabNav>>()
    val errorLiveData = MutableLiveData<Throwable>()

    private val _title = MutableLiveData<String>()
    val title: LiveData<String> = _title

    internal var multiTabLoadedFlow: Channel<List<MultiTabNav.LinkMultiTabNav>> = Channel(Channel.CONFLATED)

    init {
        // 是否是预加载完成的 multiTabNavData
        val isPreloadedMultiTabNavData =
            repository.defaultNavId.isNotEmpty()
                    && repository.defaultNavId == mMultiTabNavId
                    && repository.multiTabNavLiveData.value?.id == mMultiTabNavId
        if (isPreloadedMultiTabNavData) {
            processMultiTabNavData(repository.multiTabNavLiveData.value!!)
        } else if (mMultiTabNavId.isNotEmpty()) {
            getMultiTabNav()
        }
    }

    @SuppressLint("CheckResult")
    fun getMultiTabNav() {
        mNewApi.getTabNav(mMultiTabNavId)
            .compose(singleToMain())
            .subscribe({
                processMultiTabNavData(it)
            }, {
                errorLiveData.postValue(it)
            })
    }

    private fun processMultiTabNavData(multiTabNav: MultiTabNav) {
        _title.value = multiTabNav.title
        val tabList = multiTabNav.linkMultiTabNav
        tabList.forEachIndexed { index, tab ->
            if (tab.link?.type == ViewPagerFragmentHelper.TYPE_AMWAY) {
                tab.style.primaryColor = com.gh.gamecenter.common.R.color.amway_primary_color.toColor(getApplication())
                tab.style.useLightStyle = true
                tab.style.currentSelectColor = tab.style.primaryColor
            }

            if (tab.default) {
                defaultTabPosition = index
            }
        }

        overwriteDefaultIfNeeded(multiTabNav)

        tabListLiveData.postValue(tabList)

        // 延迟 10ms，让 viewPager 先 setAdapter 再触发页面选中
        viewModelScope.launch {
            delay(10L)
            multiTabLoadedFlow.send(tabList)
        }
    }

    open fun overwriteDefaultIfNeeded(multiTabNav: MultiTabNav) {

    }

    class Factory(private val mMultiTabNavId: String) : ViewModelProvider.NewInstanceFactory() {
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return TabWrapperViewModel(HaloApp.getInstance(), mMultiTabNavId, MainWrapperRepository.getInstance()) as T
        }
    }
}