package com.swiftcleaner.chovey.business

import com.swiftcleaner.chovey.BuildConfig
import com.swiftcleaner.chovey.GlobalConfig.PACKAGE_NAME
import com.swiftcleaner.chovey.GlobalConfig.URL_EVENT
import com.swiftcleaner.chovey.GlobalConfig.isInit
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 EventUtils {

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

    fun event(action: String, value: String? = null, ext: JSONObject? = null) {
        if (!isInit) return

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

        val json = JSONObject()
            .put("data", data)
            .put("bp", DeviceUtils.getConfigParams())
            .toString()
        val body = AESUtils.encrypt(json)
            .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) {
            }

            override fun onResponse(call: Call, response: Response) {
            }
        })
    }
}