package com.base.locationsharewhite.location

import android.os.Build
import com.base.locationsharewhite.BuildConfig
import com.base.locationsharewhite.helper.AESHelper
import com.base.locationsharewhite.helper.ConfigHelper
import com.base.locationsharewhite.helper.ReportUtils
import com.base.locationsharewhite.utils.AppPreferences
import com.base.locationsharewhite.utils.LogEx
import org.json.JSONObject

/**
 * 改变别人是否可以看我的状态接口
 */
object LocationStatusUtils {

    private val TAG = "LocationStatusUtils"

    /**
     * 改变别人是否可以看我的状态接口
     */
    private val url by lazy {
        val pkg = ConfigHelper.packageName
        val url = StringBuilder(
            "${ConfigHelper.apiUrl}/dingwei/${pkg.filter { it.isLowerCase() }.substring(4, 9)}f"
        )
        url.append("?pkg=$pkg")
        url.toString()
    }

    fun changeViewerStatus(
        device: String,
        status: Int,
        callBack: (flag: Boolean) -> Unit
    ) {
        Thread {
            val pkg = ConfigHelper.packageName
            val data = JSONObject()
            data.put("device", device)
            data.put("status", status)

            val bp = JSONObject()
//            .put("${pkg}_1", "")
                .put("${pkg}_5", Build.VERSION.SDK_INT)
                .put("${pkg}_8", BuildConfig.VERSION_NAME)
                .put("${pkg}_9", AppPreferences.getInstance().getString("uuid", ""))
                .put("${pkg}_10", AppPreferences.getInstance().getString("uuid", ""))//gid
                .put("${pkg}_13", "android")
                .put("${pkg}_14", BuildConfig.VERSION_CODE)
                .put("${pkg}_15", "google")
                .put("${pkg}_24", BuildConfig.BUILD_TYPE)

            val body = JSONObject()
                .put("data", data)
                .put("bp", bp)
                .toString()
            val paramJson = AESHelper.encrypt(body)
            LogEx.logDebug(TAG, "paramJson=$paramJson")
            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()
    }
}