package com.base.datarecovery.utils

import android.util.Log
import com.base.datarecovery.bean.ConfigBean
import com.base.datarecovery.help.ConfigHelper
import com.google.gson.Gson
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL

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

    fun doGet(): String {
        val urlPath = url
        Log.d("okhttp", urlPath ?: "")
        try {
            val conn: HttpURLConnection = URL(urlPath).openConnection() as HttpURLConnection
            conn.setRequestMethod("GET")
            conn.connectTimeout = 150000
            if (200 == conn.getResponseCode()) {
                val json = BufferedReader(InputStreamReader(conn.getInputStream())).readLine()
                Log.d("okhttp", json)
                return json
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Log.d("okhttp", e.toString())
        }
        return "{ \"success\": false,\n   \"errorMsg\": \"后台服务器开小差了!\",\n     \"result\":{}}"
    }

    fun requestCfg(callback: (ConfigBean) -> Unit) {
        val s = doGet()
        val i = Regex("\"data\":\"(.*?)\"").find(s)
        if (i.toString() != "null") {
            i!!.groupValues[1].let {
                val str = AESHelper.decrypt(it)

                val gson = Gson()
                val bean = gson.fromJson(str, Map::class.java)
//                Log.d("jiekou",str)
//                SPUtils.getInstance().put("actionS", bean.actionS);
//                SPUtils.getInstance().put("open", bean.open);
//                SPUtils.getInstance().put("num", bean.num);
//                SPUtils.getInstance().put("delay", bean.delay);
//                SPUtils.getInstance().put("lockS", bean.lockS);
//                SPUtils.getInstance().put("notification_interval", bean.notificationInterval);
//                SPUtils.getInstance().put("timerS", bean.timerS)
//                SPUtils.getInstance().put("timerDelay", bean.timerDelay)
//                SPUtils.getInstance().put("timerInterval", bean.timerInterval)
//                SPUtils.getInstance().put("naAdS", bean.naAdS)
//                adDisplayInterval = bean.adInterval
//                maxMultiClick = bean.maxMultiClick
//                AdDisplayUtils.getInstance().setMaxAdDisplayCount(bean.adShowCount)
//                AdDisplayUtils.getInstance().maxAdClickCount = bean.adClickCount
//                callback(bean)
            }
        }
    }
}