package com.gh.common.util

import com.gh.download.DownloadManager
import com.gh.gamecenter.common.utils.DialogHelper
import com.gh.gamecenter.core.runOnIoThread
import com.gh.gamecenter.core.runOnUiThread
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.login.user.UserManager
import com.gh.ndownload.NHttpClient
import com.lightgame.utils.AppManager
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStream
import java.io.InputStreamReader
import java.net.HttpURLConnection

/**
 * 一个临时用来检测实名的工具类，相关需求是这个 https://jira.shanqu.cc/browse/GHZS-4522
 */
object TempCertificationUtils {

    fun checkCertificationBeforeAction(gameEntity: GameEntity, action: () -> Unit) {
        // 更新下载相关的meta信息，用于 connection 的 header
        DownloadManager.updateDownloadMetaMap()

        runOnIoThread {
            try {
                val url = gameEntity.getApk().firstOrNull()?.url ?: return@runOnIoThread

                val client = NHttpClient()
                val connection = client.connect(url, 3000, 3000, -1, -1, -1, null)
                val code = connection.responseCode
                if (code == HttpURLConnection.HTTP_FORBIDDEN) {
                    val resultObject = JSONObject(getErrorResponse(connection.errorStream))
                    val customResponseCode = resultObject.getString("code")

                    if ("403001" == customResponseCode) {
                        // 未实名
                        runOnUiThread {
                            RealNameHelper.showRealNameUncertificatedDialog(null)
                        }
                    } else if ("403002" == customResponseCode) {
                        // 未成年
                        runOnUiThread {
                            RealNameHelper.showRealNameUnqualifiedDialog(null)
                        }
                    } else if ("403003" == customResponseCode) {
                        // 该游戏未接入防沉迷系统禁止下载
                        val currentActivity = AppManager.getInstance().currentActivity()

                        if (currentActivity != null) {
                            runOnUiThread {
                                DialogHelper.showDialog(
                                    context = currentActivity,
                                    title = "温馨提示",
                                    content = "该游戏未接入防沉迷系统，暂不支持下载",
                                    confirmText = "知道了",
                                    cancelText = ""
                                )
                            }
                        } else {
                            ToastUtils.toast("该游戏未接入防沉迷系统，暂不支持下载")
                        }
                    } else if ("403004" == customResponseCode) {
                        // 后台禁止该设备下载
                        ToastUtils.showToast("网络异常")
                    } else {
                        ToastUtils.showToast("网络异常 $customResponseCode")
                    }
                } else {
                    runOnUiThread {
                        action.invoke()
                    }
                }
            } catch (e: Exception) {
                ToastUtils.showToast("网络异常，请稍后再试 ${e.message}")
            }
        }
    }

    private fun getErrorResponse(inputStream: InputStream): String {
        val bf = BufferedReader(InputStreamReader(inputStream))
        val stringBuffer = StringBuilder()
        var strCurrentLine: String?
        while (bf.readLine().also { strCurrentLine = it } != null) {
            stringBuffer.append(strCurrentLine)
        }
        bf.close()
        return stringBuffer.toString()
    }

    /**
     * 检测光环是否实名
     */
    fun isUserVerified(): Boolean {
        val idCard = UserManager.getInstance().userInfoEntity?.idCard
        // 账号已实名
        return idCard != null && idCard.status == 0
    }
}