package com.swiftcleaner.chovey.business

import com.swiftcleaner.chovey.BuildConfig
import com.swiftcleaner.chovey.GlobalConfig.PACKAGE_NAME
import com.swiftcleaner.chovey.GlobalConfig.URL_API
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 BlacklistUtils {

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

    fun requestBlacklist(block: (Int) -> Unit) {
        val data = JSONObject()
            .put("bp", DeviceUtils.getConfigParams())
            .toString()
        val body = AESUtils.encrypt(data)
            .toRequestBody("application/json;charset=utf-8".toMediaTypeOrNull())
        val client = OkHttpClient.Builder().apply {
            if (BuildConfig.DEBUG) {
                addInterceptor(HttpLoggingInterceptor().apply {
                    level = HttpLoggingInterceptor.Level.BODY
                })
            }
        }.build()
        val request = Request.Builder()
            .url(url)
            .post(body)
            .build()
        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 = AESUtils.decrypt(it)
                            val blacklist = if (str == "true") 0 else 1
                            block.invoke(blacklist)
                        }
                    }
                }
            }
        })
    }
}