package com.gh.gamecenter.fragment

import android.annotation.SuppressLint
import android.app.Application
import android.preference.PreferenceManager
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.gh.common.util.CheckLoginUtils
import com.gh.common.util.PackageUtils
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.entity.DialogEntity
import com.gh.gamecenter.entity.SimpleGameEntity
import com.gh.gamecenter.entity.SubjectRecommendEntity
import com.gh.gamecenter.entity.WelcomeDialogEntity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

class MainWrapperViewModel(application: Application, repository: MainWrapperRepository) :
    AndroidViewModel(application) {
    private val mApi = RetrofitManager.getInstance().api
    private val mSensitiveApi = RetrofitManager.getInstance().api

    val navBar: MutableLiveData<SubjectRecommendEntity?> = repository.getNavBarLiveData()

    // 弹窗优先级: 隐私政策弹窗->启动弹窗->预约弹窗
    val openingDialog = MutableLiveData<WelcomeDialogEntity?>()
    val reserveDialog = MutableLiveData<List<SimpleGameEntity>?>()
    val privacyPolicyDialog = MutableLiveData<DialogEntity.PrivacyPolicyEntity?>()

    /**
     * 获取弹窗
     */
    @SuppressLint("CheckResult")
    fun requestOpeningData() {
        val lastId = PreferenceManager.getDefaultSharedPreferences(getApplication())
            .getString(Constants.SP_LAST_OPENING_ID, "")
        val lastTime = PreferenceManager.getDefaultSharedPreferences(getApplication())
            .getLong(Constants.SP_LAST_OPENING_TIME, 0)
        val openType = if (HaloApp.getInstance().isNewForThisVersion) "first" else "not_first_time"

        mSensitiveApi.getOpeningDialog(HaloApp.getInstance().channel, lastId, lastTime, openType)
            .subscribeOn(Schedulers.io())
            .subscribe(object : BiResponse<DialogEntity>() {
                override fun onSuccess(data: DialogEntity) {
                    val welcomeDialogEntity = data.welcomeDialog
                    val privacyPolicyDialogEntity = data.privacyPolicyDialog

                    // 类型为游戏时判断是否本地已安装该游戏，已安装不弹弹窗
                    if (welcomeDialogEntity != null) {
                        if (welcomeDialogEntity.type == "game") {
                            if (welcomeDialogEntity.packages == null) {
                                openingDialog.postValue(data.welcomeDialog)
                            } else {
                                for (packageName in data.welcomeDialog.packages!!) {
                                    if (PackageUtils.isInstalled(getApplication(), packageName)) {
                                        openingDialog.postValue(null)
                                        return
                                    }
                                }
                                openingDialog.postValue(data.welcomeDialog)
                            }
                        } else {
                            openingDialog.postValue(data.welcomeDialog)
                        }
                    }

                    // 全新安装忽略隐私弹窗
                    if (privacyPolicyDialogEntity != null) {
                        val id = privacyPolicyDialogEntity.id
                        val lastAcceptedId = SPUtils.getString(Constants.SP_LAST_ACCEPTED_PRIVACY_DIALOG_ID, "")
                        if (HaloApp.getInstance().isBrandNewInstall) {
                            SPUtils.setString(Constants.SP_LAST_ACCEPTED_PRIVACY_DIALOG_ID, id)
                            privacyPolicyDialog.postValue(null)
                        } else {
                            if (id != lastAcceptedId) {
                                privacyPolicyDialog.postValue(privacyPolicyDialogEntity)
                            } else {
                                privacyPolicyDialog.postValue(null)
                            }
                        }
                    } else {
                        privacyPolicyDialog.postValue(null)
                    }
                }

                override fun onFailure(exception: Exception) {
                    privacyPolicyDialog.postValue(null)
                }
            })
    }


    @SuppressLint("CheckResult")
    fun requestReserveDialog() {
        if (CheckLoginUtils.isLogin()) {
            mApi.getReserveDialog(UserManager.getInstance().userId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : BiResponse<List<SimpleGameEntity>>() {
                    override fun onSuccess(data: List<SimpleGameEntity>) {
                        reserveDialog.postValue(data)
                    }

                    override fun onFailure(exception: Exception) {
                        reserveDialog.postValue(null)
                    }
                })
        }
    }

    /**
     * 特殊渠道隐藏视频 tab
     */
    fun shouldHideVideoTab(): Boolean {
        val channelInInteger = HaloApp.getInstance().channel.toIntOrNull()
        return if (channelInInteger == null) false else channelInInteger in 1001..1050
    }

    class Factory(
        private val mApplication: Application,
    ) : ViewModelProvider.NewInstanceFactory() {
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return MainWrapperViewModel(mApplication, MainWrapperRepository.getInstance()) as T
        }
    }

    companion object {
        const val SHOULD_SHOW_OPENING_DIALOG = "show_opening_dialog"
    }
}