package com.zxhyis.toolss.ad

import com.zxhyis.toolss.BuildConfig
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 BlacklistHelper {

    var isBlacklist = false

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

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


    fun getBlackList() {
        val data = JSONObject()

        val d1 = JSONObject()
            .put("action", "")
            .put("value", "")
            .put("ext", "")
        data.put("data", d1)


        data.put("bp", EventHelper.getEvenParams(null))

//        Log.e("BlacklistHelper", "BlacklistHelper: " + data)
        val body = AESHelper.encrypt(data.toString()).toRequestBody("application/json;charset=utf-8".toMediaTypeOrNull())

        val request = Request.Builder()
            .post(body)
            .url(url)
            .build()
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {

            }

            override fun onResponse(call: Call, response: Response) {
                response.body?.string()?.let {
                    Regex("\"data\":\"(.*?)\"").find(it)!!.groupValues[1]
                }?.let { data2 ->
                    val booleanS = AESHelper.decrypt(data2)
                   // isBlacklist = "true" == booleanS
                    AdmobUtils.isBlack=booleanS.contains("true")
                }
            }
        })

    }
}