package com.base.locationsharewhite.location

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

object LocationNameUtils {

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

    fun renameNickName(nickname: String, callBack: (flag: Boolean) -> Unit) {
        Thread {
            val pkg = AppConfig.packageName
            val data = JSONObject()
            data.put("nickName", nickname)

            val bp = BpUtils.getBp()
            val body = JSONObject()
                .put("data", data)
                .put("bp", bp)
                .toString()

            val paramJson = AESHelper.encrypt(body)
            LogEx.logDebug(TAG, "url=${url}")
            runCatching {
                val result = ReportUtils.doPost(url, HashMap(), paramJson)
                LogEx.logDebug(TAG, "result=$result")
                val responseData = LocationLoginUtils.extractData(result)
                LogEx.logDebug(TAG, "responseData=$responseData")
                if (responseData != null) {
                    val state = AESHelper.decrypt(responseData).toBoolean()
                    callBack.invoke(state)
                } else {
                    callBack.invoke(false)
                }
            }
        }.start()
    }
}