package com.adealink.weparty.config

import com.adealink.frame.base.Rlt
import com.adealink.frame.base.fastLazy
import com.adealink.frame.frame.BaseFrame
import com.adealink.frame.frame.IBaseFrame
import com.adealink.frame.frame.IListener
import com.adealink.frame.log.Log
import com.adealink.frame.util.PackageUtil
import com.adealink.weparty.App
import com.adealink.weparty.config.data.APPROVING_VERSION_CONFIG
import com.adealink.weparty.config.data.GetGlobalConfigReq
import com.adealink.weparty.config.data.TAG_APPROVING_VERSION
import com.adealink.weparty.config.datasource.remote.ConfigHttpService
import kotlinx.coroutines.launch

interface IApprovingVersionListener : IListener {

    fun onApprovingChanged(enable: Boolean) {}

}

interface IApprovingVersionManager : IBaseFrame<IApprovingVersionListener> {

    fun isApproving(): Boolean

    fun getApprovingVersion(): Int?

    /**
     * 强制获取Approving状态
     */
    fun refreshApproving()

}

val approvingVersionManager: IApprovingVersionManager by lazy { ApprovingVersionManager() }

class ApprovingVersionManager : BaseFrame<IApprovingVersionListener>(), IApprovingVersionManager {

    private val configHttpService by fastLazy {
        App.instance.networkService.getHttpService(ConfigHttpService::class.java)
    }
    private var approving: Boolean = true
    private var approvingVersion: Int? = null

    init {
        refreshApproving()
    }


    override fun isApproving(): Boolean {
        return approving
    }

    override fun getApprovingVersion(): Int? {
        return approvingVersion
    }

    override fun refreshApproving() {
        launch {
            val rlt = configHttpService.getApprovingVersion(
                GetGlobalConfigReq(listOf(APPROVING_VERSION_CONFIG))
            )
            when (rlt) {
                is Rlt.Failed -> {
                    Log.e(TAG_APPROVING_VERSION, "getApprovingVersion fail, $rlt")
                }

                is Rlt.Success -> {
                    val version = rlt.data.data?.configs?.version
                    approvingVersion = version
                    approving = PackageUtil.getVersionCode() >= (version ?: 0)
                    notifyApprovingChanged(approving)
                }
            }
        }
    }

    private fun notifyApprovingChanged(approving: Boolean) {
        dispatch {
            it.onApprovingChanged(approving)
        }
    }

}