package com.gh.gamecenter.oaid

import android.annotation.SuppressLint
import android.content.Context
import com.therouter.router.Route
import com.bun.miitmdid.core.MdidSdkHelper
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.core.provider.IOAIDProvider
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.oaid.network.CertEntity
import com.gh.gamecenter.oaid.network.RetrofitManager
import com.lightgame.utils.Utils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

@com.therouter.inject.ServiceProvider
class OAIDProviderImpl : IOAIDProvider {

    override fun doSystemLoad() {
        // android 6.0 以下不支持获取 OAID
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.M) return

        System.loadLibrary("msaoaidsec")
    }

    override fun getOAID(context: Context, callback: (String, Boolean) -> Unit) {
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.M) return

        val cachedCert = SPUtils.getString(SP_OAID_CERT)

        // 若存在缓存的证书，优先使用缓存的证书来初始化
        if (cachedCert.isNotEmpty()) {
            Utils.log(TAG, "使用缓存的证书来初始化 $cachedCert")

            var result = false
            try {
                result = MdidSdkHelper.InitCert(context, cachedCert)
            } catch (e: Throwable) {
                e.printStackTrace()

                Utils.log(TAG, "初始化证书异常 ${e.localizedMessage}")
            }

            Utils.log(TAG, "初始化证书结果 $result")

            getOAIDForReal(context, true, callback)
        } else {
            getCertFromServerThenGetOAID(context, callback)
        }
    }

    @SuppressLint("CheckResult")
    private fun getCertFromServerThenGetOAID(context: Context, callback: (String, Boolean) -> Unit) {
        RetrofitManager.getInstance().api.getOAIDCert()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<CertEntity>() {
                override fun onSuccess(data: CertEntity) {
                    Utils.log(TAG, "获取到的证书为 ${data.cert}")

                    var result = false
                    try {
                        result = MdidSdkHelper.InitCert(context, data.cert)
                    } catch (e: Throwable) {
                        e.printStackTrace()

                        Utils.log(TAG, "初始化证书异常 ${e.localizedMessage}")
                    }

                    SPUtils.setString(SP_OAID_CERT, data.cert)

                    Utils.log(TAG, "初始化证书结果 $result")

                    getOAIDForReal(context, false, callback)
                }

                override fun onFailure(exception: Exception) {
                    super.onFailure(exception)
                    Utils.log(TAG, "获取证书异常")
                }
            })
    }

    private fun getOAIDForReal(context: Context, fromCached: Boolean, callback: (String, Boolean) -> Unit) {
        try {
            val code = MdidSdkHelper.InitSdk(context, false, true, false, false) { p0 ->
                p0?.oaid?.let {
                    callback.invoke(it, true)
                }
            }

            Utils.log(TAG, "获取 OAID 的返回值为 $code")

            // 缓存的证书失效了，访问接口重新获取
            if (fromCached && code == 1008616) {
                getCertFromServerThenGetOAID(context, callback)
            } else if (code == 1008611 || code == 1008612 || code == 1008613 || code == 1008615) {
                // 返回错误
                callback.invoke("", false)
            }
        } catch (t: Throwable) {
            t.printStackTrace()
            Utils.log(TAG, "初始化 OAID 异常")
        }
    }

    companion object {
        private const val TAG = "oaid"
        private const val SP_OAID_CERT = "oaid_cert"
    }
}