package melody.offline.music.http

import android.content.Context
import com.google.gson.Gson
import org.json.JSONException
import org.json.JSONObject
import melody.offline.music.App
import melody.offline.music.util.AesEncryptUtil
import java.util.Locale
import java.util.UUID


class BaseApiUtil {

    companion object {
        val shared: BaseApiUtil by lazy { BaseApiUtil() }
        const val initialAddress = "/"
        const val key = "7387m0ax5x0n5tca"
        const val iv = "D4Q1ymaIHSYifWS9"

        const val getIPInfoUrl = "/app/common/getIPInfo"
        const val getAppDataURL = "/statistic/appdatacollection/saveAppData"

        const val BaseUrl = "https://api.tikustok.com"
    }

    private fun PostContentMessage.toJson(): String {
        val gson = Gson()
        return gson.toJson(this)
    }

    private fun PostContentSecurityBody.toJson(): String {
        val gson = Gson()
        return gson.toJson(this)
    }

    fun initPostBody(
        method: String,
        url: String,
        query: HashMap<String, String>,
        json: JSONObject? = null,
        currentBaseUrl: String? = null
    ): String {
        val randomStr = UUID.randomUUID().toString().replace("-", "")

        val headers: HashMap<String, String> = HashMap()
        headers["request_userid"] = userID(App.app)
        headers["request_pkgname"] = packageName
        headers["base_url"] = currentBaseUrl + ""
        headers["request_deviceid"] = getUUId(App.app)
        headers["request_id"] = UUID.randomUUID().toString()

        val requestId = UUID.randomUUID().toString()
        val timestamp = "TS" + System.currentTimeMillis()

        val trueBody = PostContentMessage(
            requestId,
            method,
            url,
            query,
            headers,
            json.toString(),
            timestamp,
            randomStr
        )
        val jsonString = trueBody.toJson()
        val encryptJsonString = AesEncryptUtil.encrypt(jsonString, key, iv)
        val postContentSecurityBody = PostContentSecurityBody(method, encryptJsonString)
        return postContentSecurityBody.toJson()
    }


    fun postJson(context: Context, eventName: String?): JSONObject {
        val jsonObject = JSONObject()
        try {
            jsonObject.put("eventName", eventName)
            jsonObject.put("timestamp", System.currentTimeMillis())
            jsonObject.put("uuid", getUUId(context))
            jsonObject.put("app_version_name", getAppVersionName(context))
            jsonObject.put("app_version_code", getAppVersionCode(context))
            jsonObject.put("channel", "google")
            jsonObject.put("country", getCountry(context))
            jsonObject.put("device", "android")
            jsonObject.put("language", Locale.getDefault().language)
            jsonObject.put("pkgName", context.packageName)
            jsonObject.put("userId", userID(context))
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return jsonObject
    }

    //需要添加gaid的json组装
    fun postJson(context: Context, eventName: String?, gaId: String?): JSONObject {
        val jsonObject = postJson(context, eventName)
        try {
            jsonObject.put("adId", gaId)
        } catch (e: JSONException) {
            throw RuntimeException(e)
        }
        return jsonObject
    }
}