package com.base.locationsharewhite.location

import com.base.locationsharewhite.helper.AESHelper
import com.base.locationsharewhite.helper.ReportUtils
import com.base.locationsharewhite.helper.AppConfig
import com.base.locationsharewhite.location.LocationLoginUtils.extractData
import com.base.locationsharewhite.utils.AppPreferences
import com.base.locationsharewhite.utils.LogEx
import org.json.JSONObject

/**
 * 通过邀请码建立分享关系
 */
object LocationShareUtils {

    private val TAG = "LocationShareUtils"

    const val SHARE_STATE_FAILED = 0
    const val SHARE_STATE_SUCCESS = 1
    const val SHARE_STATE_SHARED = 2
    const val SHARE_STATE_MYSELF = 3

    /**
     * 分享位置接口
     */
    private val url by lazy {
        val pkg = AppConfig.packageName
        val url = StringBuilder(
            "${AppConfig.apiUrl}/dingwei/${pkg.filter { it.isLowerCase() }.substring(4, 9)}m"
        )
        url.append("?pkg=$pkg")
        url.toString()
    }

    fun shareMyLocationByInvitationCode(
        invitationCode: String,
        callBack: (state: Int) -> Unit
    ) {
        Thread {

            val data = JSONObject()
            data.put("invitationCode", invitationCode)
            LogEx.logDebug(TAG, "invitationCode=${invitationCode}")
            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, "paramJson=$paramJson")
            runCatching {
                val result = ReportUtils.doPost(url, HashMap(), paramJson)
                LogEx.logDebug(TAG, "result=$result")
                val responseData = extractData(result)
                if (responseData != null) {
                    val state = AESHelper.decrypt(responseData).toInt()
                    callBack.invoke(state)
                } else {
                    callBack.invoke(0)
                }
            }
        }.start()
    }
}