package com.gh.common.util

import android.annotation.SuppressLint
import com.gh.gamecenter.common.entity.SignatureEntity
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.common.utils.toJson
import com.gh.gamecenter.common.utils.toObject
import com.gh.gamecenter.core.utils.MD5Utils
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.retrofit.RetrofitManager
import io.reactivex.schedulers.Schedulers

/**
 * 存储光环网游使用的签名
 */
object SignatureRepository {

    private const val SP_SIGN_DIGEST_LIST = "sign_digest_list"

    private var signDigestList: ArrayList<String>? = null

    @SuppressLint("CheckResult")
    fun init() {
        RetrofitManager.getInstance()
            .newApi
            .ghSignature
            .subscribeOn(Schedulers.io())
            .subscribe(object : BiResponse<ArrayList<SignatureEntity>>() {
                override fun onSuccess(data: ArrayList<SignatureEntity>) {
                    signDigestList = ArrayList()

                    for (i in data) {
                        signDigestList?.add(i.signMd5)
                    }

                    SPUtils.setString(SP_SIGN_DIGEST_LIST, signDigestList?.toJson() ?: "")
                }

                override fun onFailure(exception: Exception) {
                    super.onFailure(exception)

                    signDigestList = SPUtils.getString(SP_SIGN_DIGEST_LIST).toObject()
                }
            })
    }

    /**
     * 签名列表是否为空
     */
    @JvmStatic
    fun isSignEmpty(): Boolean {
        return signDigestList.isNullOrEmpty()
    }

    /**
     * 签名是否匹配已知的签名
     */
    @JvmStatic
    fun isSignMatched(sign: String): Boolean {
        val signDigest = MD5Utils.getContentMD5(sign)

        return signDigestList?.contains(signDigest) == true
    }

}