package com.xm.test.myfilemaster

import android.os.Build
import android.util.Log
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.NetworkUtils
import com.blankj.utilcode.util.ScreenUtils
import com.xm.test.myfilemaster.ad.AESHelper
import com.xm.test.myfilemaster.ad.ConfigHelper
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
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 org.json.JSONObject
import java.io.IOException

fun netSendEvent(key: String, value: String? = null, ext: JSONObject? = null) {
    val pkg = ConfigHelper.packageName
    val d1 = JSONObject()
        .put("action", key)
        .put("value", value)
        .put("ext", ext)

    val d2 = JSONObject()
        .put("${pkg}_1", "${ScreenUtils.getScreenHeight()}")
        .put("${pkg}_2", "${ScreenUtils.getScreenWidth()}")
        .put("${pkg}_3", DeviceUtils.getModel())
        .put("${pkg}_4", Build.MANUFACTURER)
        .put("${pkg}_5", Build.VERSION.SDK_INT)
        .put("${pkg}_6", "${NetworkUtils.getNetworkType()}")
        .put("${pkg}_8", AppUtils.getAppVersionName())
        .put("${pkg}_9", DeviceUtils.getAndroidID())
        .put("${pkg}_10", ConfigHelper.gid)
        .put("${pkg}_11", System.getProperty("http.agent"))
        .put("${pkg}_13", "android")
        .put("${pkg}_14", "${AppUtils.getAppVersionCode()}")
        .put("${pkg}_15", "google")
//        .put("${pkg}_24",BuildConfig.BUILD_TYPE)

    val data = JSONObject()
        .put("data", d1)
        .put("bp", d2)
        .toString()

    val body =
        AESHelper.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(eventUrl)
        .post(body)
        .build()

    CoroutineScope(Dispatchers.IO).launch {
        delay(1000)

        client.newCall(request = request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                Log.d("glc", "onFailure:${e.message}")
            }

            override fun onResponse(call: Call, response: Response) {
                Log.d("glc","net success")
            }

        })

    }

}

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