package com.base.locationsharewhite.location

import com.base.locationsharewhite.bean.LocationData
import com.base.locationsharewhite.helper.AESHelper
import com.base.locationsharewhite.helper.ReportUtils
import com.base.locationsharewhite.helper.config.AppConfig
import com.base.locationsharewhite.utils.AppPreferences
import com.base.locationsharewhite.utils.LogEx
import com.google.android.gms.maps.model.LatLng
import com.google.gson.Gson
import org.json.JSONObject

/**
 * 上报自身位置
 */
object LocationPositionUtils {

    private val TAG = "LocationPositionUtils"

    /**
     * 上传定位接口
     */
    private val uploadUrl by lazy {
        val pkg = AppConfig.packageName
        val url = StringBuilder(
            "${AppConfig.apiUrl}/dingwei/${pkg.filter { it.isLowerCase() }.substring(4, 9)}x"
        )
        url.append("?pkg=$pkg")
        url.toString()
    }

    /**
     *上传自身位置
     */
    fun uploadMyLocation(latLng: LatLng, power: Int) {
        Thread {
            val data = JSONObject()
            data.put("latitude", latLng.latitude)
            data.put("longitude", latLng.longitude)
            data.put("power", power)
            data.put("timezone", System.currentTimeMillis())
            LogEx.logDebug(TAG, "uploadMyLocation uuid=${AppPreferences.getInstance().getString("uuid", "")}")
            LogEx.logDebug(TAG, "uploadMyLocation latitude=${latLng.latitude} longitude=${latLng.longitude} power=$power")
            val bp = BpUtils.getBp()
            val body = JSONObject()
                .put("data", data)
                .put("bp", bp)
                .toString()

            val paramJson = AESHelper.encrypt(body)
            LogEx.logDebug(TAG, "uploadMyLocation paramJson=${paramJson}")
            runCatching {
                LogEx.logDebug(TAG, "uploadMyLocation uploadUrl=${uploadUrl}")
                val result = ReportUtils.doPost(uploadUrl, HashMap(), paramJson)
                LogEx.logDebug(TAG, "result=$result")
            }
        }.start()
    }


    /**
     * 获取定位接口
     */
    private val getLatLngUrl by lazy {
        val pkg = AppConfig.packageName
        val url = StringBuilder(
            "${AppConfig.apiUrl}/dingwei/${pkg.filter { it.isLowerCase() }.substring(4, 9)}u"
        )
        url.append("?pkg=$pkg")
        url.toString()
    }

    /**
     * 获取定位信息
     */
    fun getLocation(
        device: String,
        callBack: ((locationData: LocationData?) -> Unit)? = null
    ) {
        Thread {

            val data = JSONObject()
            data.put("device", device)
            LogEx.logDebug(TAG, "getLocation device=$device")

            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)
            runCatching {
                val result = ReportUtils.doPost(getLatLngUrl, HashMap(), paramJson)
                LogEx.logDebug(TAG, "getLocation result=$result")
                val responseData = LocationLoginUtils.extractData(result)
                if (responseData != null) {
                    val decryptedData = AESHelper.decrypt(responseData)
                    LogEx.logDebug(TAG, "getLocation decryptedData=$decryptedData")
                    val locationData: LocationData? = parseLoginData(decryptedData)
                    callBack?.invoke(locationData)
                }
            }
        }.start()
    }

    private fun parseLoginData(decryptedData: String): LocationData? {
        val gson = Gson()
        val locationData = gson.fromJson(decryptedData, LocationData::class.java)
        LogEx.logDebug(TAG, "locationData=$locationData")
        return locationData
    }
}