package com.base.scanqrclear.luma

import android.util.Base64
import com.base.scanqrclear.BuildConfig
import com.base.scanqrclear.GlobalConfig.PACKAGE_NAME
import com.base.scanqrclear.GlobalConfig.URL_API
import com.base.scanqrclear.helper.EventUtils
import com.base.scanqrclear.luma.AdmobHelps.KEY_GOOGLE_ADVERTISER_ID
import com.base.scanqrclear.luma.AdmobHelps.KEY_REFERRER
import com.base.scanqrclear.luma.AdmobHelps.KEY_UUID
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import okhttp3.Call
import okhttp3.Callback
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import org.json.JSONObject
import java.io.IOException

object APIUtils {

    private val configUrl by lazy {
        val url = StringBuilder("${URL_API}/${PACKAGE_NAME.filter { it.isLowerCase() }.substring(4, 9)}spk")
        url.append("?pkg=$PACKAGE_NAME")
        val referrer = SpUtils.getInstance().getString(KEY_REFERRER)
        url.append("&referrer=${Base64.encodeToString(referrer.toByteArray(), Base64.DEFAULT)}")
        url.append("&vn=${BuildConfig.VERSION_NAME}")
        url.append("&vc=${BuildConfig.VERSION_CODE}")
        url.append("&device=${SpUtils.getInstance().getString(KEY_GOOGLE_ADVERTISER_ID)}")
        url.append("&aid=${SpUtils.getInstance().getString(KEY_UUID)}")
        url.append("&mode=4")
        url.toString()
    }

    private val blacklistUrl by lazy {
        val url = StringBuilder("${URL_API}/${PACKAGE_NAME.filter { it.isLowerCase() }.substring(4, 9)}cl")
        url.append("?pkg=${PACKAGE_NAME}")
        url.toString()
    }

    fun requestConfig(block: () -> Unit) {
        val request = Request.Builder()
            .url(configUrl)
            .get()
            .build()
        val client = createOkHttpClient()
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                EventUtils.event("api_config_error", value = e.toString())
            }

            override fun onResponse(call: Call, response: Response) {
                response.body?.string()?.let {
                    val result = Regex("\"data\":\"(.*?)\"").find(it)
                    if (result != null && result.toString() != "null") {
                        result.groupValues[1].let {
                            try {
                                val str = AESHelps.decrypt(it)
                                val gson = Gson()
                                val type = object : TypeToken<Map<String, Int>>() {}.type
                                val configMap = gson.fromJson<Map<String, Int>>(str, type)
                                configMap.forEach { (t, u) ->
                                    SpUtils.getInstance().put(t, u)
                                }
                                block.invoke()
                                val jsonObject = JSONObject()
                                jsonObject.put("ut", SpUtils.getInstance().getInt("ut"))
                                EventUtils.event("user_type", ext = jsonObject)
                            } catch (_: Exception) {
                            }
                        }
                    }
                }

            }
        })
    }

    fun requestBlacklist() {
        val data = JSONObject()
            .put("bp", DeviceHelps.getConfigParams())
            .toString()
        val body = AESHelps.encrypt(data)
            .toRequestBody("application/json;charset=utf-8".toMediaTypeOrNull())

        val request = Request.Builder()
            .url(blacklistUrl)
            .post(body)
            .build()
        val client = createOkHttpClient()
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                EventUtils.event("api_blacklist_error", value = e.toString())
            }

            override fun onResponse(call: Call, response: Response) {
                response.body?.string()?.let {
                    val result = Regex("\"data\":\"(.*?)\"").find(it)
                    if (result != null && result.toString() != "null") {
                        result.groupValues[1].let {
                            val str = AESHelps.decrypt(it)
                            val blacklist = if (str == "true") 0 else 1
//                            GlobalConfig.blacklist = blacklist
                        }
                    }
                }
            }
        })
    }

    private fun createOkHttpClient(): OkHttpClient {
        val client = OkHttpClient.Builder().apply {
            if (BuildConfig.DEBUG) {
                addInterceptor(HttpLoggingInterceptor().apply {
                    level = HttpLoggingInterceptor.Level.BODY
                })
            }
        }.build()
        return client
    }
}