package com.adealink.weparty.config

import com.adealink.frame.data.json.froJsonErrorNull
import com.adealink.frame.frame.BaseFrame
import com.adealink.frame.frame.IBaseFrame
import com.adealink.frame.frame.IListener

interface IApprovingVersionListener : IListener {

    fun onApprovingChanged(enable: Boolean) {}

}

interface IApprovingVersionManager : IBaseFrame<IApprovingVersionListener> {

    fun isApproving(): Boolean

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

}

val approvingVersionManager: IApprovingVersionManager by lazy { ApprovingVersionManager() }

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

    private var approving: Boolean = true

    init {
        globalConfigManager.addListener(GlobalConfigType.GLOBAL_APPROVING_VERSION, this)

        refreshApproving()
    }

    override fun isApproving(): Boolean {
        return approving
    }

    override fun refreshApproving() {
        globalConfigManager.getGlobalConfig(true, GlobalConfigType.GLOBAL_APPROVING_VERSION)
    }

    private fun getApprovingBy(configJson: String?): Boolean {
        val config: ApprovingVersionConfig? = froJsonErrorNull(configJson)
        return config?.isApproving() ?: false
    }

    private fun handleApprovingChanged(configJson: String?) {
        val newApproving = getApprovingBy(configJson)
        if (approving != newApproving) {
            approving = newApproving
            notifyApprovingChanged(approving)
        }
    }

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

    override fun onConfigGet(configType: GlobalConfigType, config: List<String>) {
        if (configType == GlobalConfigType.GLOBAL_APPROVING_VERSION) {
            handleApprovingChanged(config.firstOrNull())
        }
    }

}