package com.base.locationsharewhite.location

import com.base.locationsharewhite.bean.ViewerBean
import com.base.locationsharewhite.bean.ViewingBean
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 com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import org.json.JSONObject
import java.lang.reflect.Type


/**
 * 获取分享关系列表
 */
object LocationShareListUtils {

    private val TAG = "LocationShareListUtils"

    /**
     * 分享关系列表
     */
    private val url by lazy {
        val pkg = ConfigHelper.packageName
        val url = StringBuilder(
            "${ConfigHelper.apiUrl}/dingwei/${pkg.filter { it.isLowerCase() }.substring(4, 9)}ac"
        )
        url.append("?pkg=$pkg")
        url.toString()
    }

    fun getShareList(
        viewerListCallBack: ((viewerList: List<ViewerBean>) -> Unit)? = null,
        viewingListCallBack: ((viewingList: List<ViewingBean>) -> Unit)? = null
    ) {
        Thread {

            val data = JSONObject()
            val bp = BpUtils.getBp()

            val body = JSONObject()
                .put("data", data)
                .put("bp", bp)
                .toString()
            LogEx.logDebug(TAG, "uuid=${AppPreferences.getInstance().getString("uuid", "")}")
            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 decryptedData = AESHelper.decrypt(responseData)
                    LogEx.logDebug(TAG, "decryptedData=$decryptedData")
                    parseShareListData(decryptedData, viewerListCallBack, viewingListCallBack)
                }
            }
        }.start()
    }

    private fun parseShareListData(
        decryptedData: String,
        viewerListCallBack: ((viewerList: List<ViewerBean>) -> Unit)? = null,
        viewingListCallBack: ((viewingList: List<ViewingBean>) -> Unit)? = null
    ) {
        val gson = Gson()
        val viewerListType: Type = object : TypeToken<List<ViewerBean>>() {}.type
        val viewingListType: Type = object : TypeToken<List<ViewingBean>>() {}.type

        val jsonObject = JSONObject(decryptedData)

        val viewerListJson = jsonObject.getJSONArray("viewerList").toString()
        LogEx.logDebug(TAG, "viewerListJson=$viewerListJson")
        val viewerList: List<ViewerBean> = gson.fromJson(viewerListJson, viewerListType)
        viewerListCallBack?.invoke(viewerList)

        val viewingListJson = jsonObject.getJSONArray("viewingList").toString()
        LogEx.logDebug(TAG, "viewingListJson=$viewingListJson")
        val viewingList: List<ViewingBean> = gson.fromJson(viewingListJson, viewingListType)
        LogEx.logDebug(TAG, "viewingList size=${viewingList.size}")
        viewingListCallBack?.invoke(viewingList)
    }


    /**
     * 分享关系列表
     */
    private val deleteUrl by lazy {
        val pkg = ConfigHelper.packageName
        val url = StringBuilder(
            "${ConfigHelper.apiUrl}/dingwei/${pkg.filter { it.isLowerCase() }.substring(4, 9)}p"
        )
        url.append("?pkg=$pkg")
        url.toString()
    }


    fun deleteViewer(device: String, callBacK: (result: Boolean) -> Unit) {
        Thread {
            val data = JSONObject()
            data.put("device", device)

            val bp = BpUtils.getBp()

            val body = JSONObject()
                .put("data", data)
                .put("bp", bp)
                .toString()
            val paramJson = AESHelper.encrypt(body)
            runCatching {
                val result = ReportUtils.doPost(deleteUrl, HashMap(), paramJson)
                LogEx.logDebug(TAG, "result=$result")
                val responseData = LocationLoginUtils.extractData(result)
                LogEx.logDebug(TAG, "responseData=$responseData")
                if (responseData != null) {
                    val decryptedData = AESHelper.decrypt(responseData)
                    LogEx.logDebug(TAG, "decryptedData=$decryptedData")
                    callBacK.invoke(decryptedData.toBoolean())
                }
            }
        }.start()
    }

}