package com.base.locationsharewhite.location

import com.base.locationsharewhite.helper.AESHelper
import com.base.locationsharewhite.helper.ReportUtils.doPost
import com.base.locationsharewhite.helper.config.AppConfig
import com.base.locationsharewhite.utils.AppPreferences
import com.base.locationsharewhite.utils.LogEx
import org.json.JSONObject

/**
 * 登录
 */
object LocationLoginUtils {

    var invitationCodeSp = ""
        get() {
            return AppPreferences.getInstance().getString("invitationCodeSp", field)
        }
        set(value) {
            field = value
            AppPreferences.getInstance().put("invitationCodeSp", value, true)
        }
    var myNickNameSp = ""
        get() {
            return AppPreferences.getInstance().getString("myNickNameSp", field)
        }
        set(value) {
            field = value
            AppPreferences.getInstance().put("myNickNameSp", value, true)
        }

    private val TAG = "LocationLoginUtils"
    private const val DATA_KEY = "data"

    private val url by lazy {
        val pkg = AppConfig.packageName
        val url = StringBuilder(
            "${AppConfig.apiUrl}/dingwei/${pkg.filter { it.isLowerCase() }.substring(4, 9)}v"
        )
        url.append("?pkg=$pkg")
        url.toString()
    }

    var loginCallBack: (() -> Unit)? = null

    fun login(name: String? = null) {
        Thread {

            val data = JSONObject()
            name?.let { data.put("nickName", it) }

            val bp = BpUtils.getBp()

            LogEx.logDebug(TAG, "uuid=${AppPreferences.getInstance().getString("uuid", "")}")
            val body = JSONObject()
                .put("data", data)
                .put("bp", bp)
                .toString()

            val paramJson = AESHelper.encrypt(body)
            LogEx.logDebug(TAG, "url=$url")

            runCatching {
                val result = doPost(url, HashMap(), paramJson)
                LogEx.logDebug(TAG, "result=$result")
                val responseData = extractData(result)
                LogEx.logDebug(TAG, "responseData=$responseData")
                if (responseData != null) {
                    val decryptedData = AESHelper.decrypt(responseData)
                    LogEx.logDebug(TAG, "decryptedData=$decryptedData")
                    parseLoginData(decryptedData)
                }
            }
        }.start()

    }

    fun extractData(response: String): String? {
        val regex = Regex("\"$DATA_KEY\":\"(.*?)\"")
        val match = regex.find(response)
        return match?.groupValues?.get(1)
    }

    private fun parseLoginData(json: String) {
        val data: JSONObject = JSONObject(json)

        val invitationCode = data.getString("invitationCode")
        invitationCodeSp = invitationCode

        val nickName = data.getString("nickName")
        myNickNameSp = nickName

        LogEx.logDebug(TAG, "invitationCode=$invitationCode nickName=$nickName")
        loginCallBack?.invoke()
        loginCallBack = null
    }

}