package melody.offline.music.activity

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LifecycleOwner
import melody.offline.music.http.getAppVersionCode
import melody.offline.music.http.getCountryCode
import melody.offline.music.sp.AppStore
import melody.offline.music.util.LogTag
import org.json.JSONObject

open class BaseActivity : AppCompatActivity(), LifecycleOwner {
    protected val TAG = LogTag.VO_ACT_LOG
    protected val appStore by lazy { AppStore(this) }

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

    override fun onStart() {
        super.onStart()
    }

    fun withPermission(): Boolean {
        //先判断当前配置的开关是否为true，为false的话就直接进入A
        val jsonString = appStore.shouldEnterMusicPageJson//得到配置的json
        LogTag.LogD(TAG, "BaseActivity withPermission jsonString->${jsonString}")
        val json = JSONObject(jsonString)
        val versionCode = json.optInt("versionCode")//得到配置的code
        val enter = json.optBoolean("enter")//得到配置的开关
        val currentVersionCode = getAppVersionCode(this)//得到当前应用的code
        //如果配置的code 等于 当前app的code，则把配置赋值给shouldEnterMusicPage
        if (versionCode.toLong() == currentVersionCode) {
            appStore.shouldEnterMusicPage = enter
        } else {
            appStore.shouldEnterMusicPage = true
        }
        LogTag.LogD(TAG, "BaseActivity withPermission shouldEnterMusicPage->${appStore.shouldEnterMusicPage}")
        return appStore.shouldEnterMusicPage
//        // 不允许的国家代码
//        val restrictedCountries = setOf(
////            "CN",
//            "HK",
//            "TW",
//            "JP",
//            "KR",
////            "GB",
////            "CH",
////            "BE",
////            "MO",
////            "SG"
//        )
//        // 检查是否包含当前的国家代码
//        LogTag.LogD(TAG, "BaseActivity withPermission ipCountryCode->${appStore.ipCountryCode}")
//        if (appStore.ipCountryCode in restrictedCountries) {
//            return false
//        }
//        // 如果不在受限国家代码中，则继续其他检查
//        return withIso()
    }

    private fun withIso(): Boolean {
        //460 || 461 China (People's Republic of)
        //454 "Hong Kong, China"
        //466 "Taiwan, China"
        //440 || 441 Japan
        //450 Korea (Republic of)
        //234 || 235 United Kingdom of Great Britain and Northern Ireland
        //228 Switzerland (Confederation of)
        //206 Belgium
        //455 "Macao, China"
        //525 Singapore (Republic of)
        val restrictedCountryCodes = setOf(
//                "460",
//                "461",
            "454",
            "466",
            "440",
            "441",
            "450",
//            "234", "235", "228", "206", "455", "525"
        )
        val currentCountryCode = getCountryCode(this)
        return currentCountryCode !in restrictedCountryCodes
    }
}