package com.base.scanqrclear.luma

import android.text.TextUtils
import android.util.Log
import com.base.scanqrclear.BuildConfig
import com.base.scanqrclear.GlobalConfig
import com.base.scanqrclear.bean.WeatherBean
import com.base.scanqrclear.helper.AESHelper
import com.base.scanqrclear.utils.AppPreferences
import com.base.scanqrclear.utils.LogEx
import com.google.gson.Gson
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.concurrent.TimeUnit


//object WeatherUtils {
//
//    private const val TAG = "WeatherUtils"
//
//    private val url by lazy {
//        val pkg = ConfigHelper.packageName
//        val pkgSubString = pkg.filter { it.isLowerCase() }.substring(4, 9)
//        val url = StringBuilder("${ConfigHelper.apiUrl}/city/${pkgSubString}tq")
////        url.append("?pkg=$pkg")
//        url.append("?data=${SimpleDateFormat("yyyyMMMdd").format(System.currentTimeMillis())}")
//        url.toString()
//    }
//
//    fun getWeather(): WeatherCityBean? {
//
//        val client = OkHttpClient.Builder()
//            .apply {
//                if (BuildConfig.DEBUG) {
//                    addInterceptor(HttpLoggingInterceptor().apply {
//                        level = HttpLoggingInterceptor.Level.BODY
//                    })
//                }
//                connectTimeout(10, TimeUnit.SECONDS)
//                readTimeout(20, TimeUnit.SECONDS)
//                writeTimeout(15, TimeUnit.SECONDS)
//            }.build()
//
//        LogEx.logDebug(TAG, "url=$url")
//        val request = Request.Builder()
//            .url(url)
//            .build()
//
//        val response = client.newCall(request).execute()
//        response.body?.string()?.let {
//            LogEx.logDebug(TAG, it)
//            val dataJson = getDataJson(it)
//            LogEx.logDebug(TAG, "dataJson=$dataJson")
//            return parseWeather(dataJson)
//        }
//        return null
//    }
//
//    private fun parseWeather(dataJson: String): WeatherCityBean? {
//        return try {
//            Gson().fromJson(dataJson, WeatherCityBean::class.java)
//        } catch (e: Exception) {
//            LogEx.logDebug(TAG, "$e")
//            null
//        }
//    }
//
//    private fun getDataJson(jsonString: String): String {
//        val jsonRootObject = JsonParser.parseString(jsonString).getAsJsonObject()
//        return jsonRootObject["result"].getAsJsonObject()["data"].toString()
//    }
//
//
//}


object WeatherUtils {
    fun getWeatherType(param: Int): String {
        val sunny_day: IntArray = intArrayOf(100, 101, 102, 103, 150, 151, 152, 153)
        val cloudy_day: IntArray = intArrayOf(104)
        val rainy_day: IntArray =
            intArrayOf(300, 301, 302, 303, 304, 305, 306, 307, 307, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 350, 351, 399)
        val snowy_day: IntArray = intArrayOf(400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 456, 457, 499)
        val greasy_day: IntArray = intArrayOf(500, 501, 502, 503, 504, 505, 507, 508, 509, 510, 511, 512, 513, 514, 515)

        when (param) {
            in sunny_day -> return "Sunny day"
            in cloudy_day -> return "Cloudy day"
            in rainy_day -> return "Rainy day"
            in snowy_day -> return "Snowy day"
            in greasy_day -> return "Greasy day"
            else -> return "Unknown"
        }
    }

    fun hasWeatherDataToday(): Boolean {
        return !TextUtils.isEmpty(getWeatherJsonStr())
    }

    fun getWeatherJsonStr(): String {
        val data = AppPreferences.getInstance().getString(getTodayStr() + "_weather", "")

        return data
    }

    fun getWeatherEntity(): WeatherBean? {
        val str = getWeatherJsonStr()
        Log.d("glc", str)
        if (TextUtils.isEmpty(str)) {
            requestWeatherData()
        } else {
            try {
                val gson = Gson()
                val wBean = gson.fromJson(str, WeatherBean::class.java)
                return wBean
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return null
    }


    private val url by lazy {
        val pkg = GlobalConfig.PACKAGE_NAME
        val url = StringBuilder(
            "${GlobalConfig.URL_API}/city/${
                pkg.filter { it.isLowerCase() }.substring(4, 9)
            }tq"
        )
        url.append("?pkg=$pkg")
        val sdf = SimpleDateFormat("yyyyMMdd")
        url.append("&date=${sdf.format(Calendar.getInstance().time)}")
        url.toString()
    }

    fun requestWeatherData() {
        val client = OkHttpClient.Builder().apply {
            if (BuildConfig.DEBUG) {
                addInterceptor(HttpLoggingInterceptor().apply {
                    level = HttpLoggingInterceptor.Level.BODY
                })
            }
        }.build()
        val request = Request.Builder()
            .url(url)
            .get()
            .build()
        LogEx.logDebug("requestWeatherData", "url=$url")
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {

            }

            override fun onResponse(call: Call, response: Response) {
                response.body?.string()?.let {
                    LogEx.logDebug("requestWeatherData", "it=$it")
                    val i = Regex("\"data\":\"(.*?)\"").find(it)
                    if (i.toString() != "null") {
                        i?.groupValues?.get(1).let {
                            LogEx.logDebug("requestWeatherData", "it=$it")
                            if (!TextUtils.isEmpty(it)) {
                                val str = AESHelper.decrypt(it!!)
                                LogEx.logDebug("requestWeatherData", "str=$str")
                                saveWeatherData(str)
                            }
                        }
                    }
                }

            }
        })
    }

    /**
     * 同步
     */
    fun getWeatherData() = runCatching {
        val client = OkHttpClient.Builder().apply {
            if (BuildConfig.DEBUG) {
                addInterceptor(HttpLoggingInterceptor().apply {
                    level = HttpLoggingInterceptor.Level.BODY
                })
            }
        }.connectTimeout(1, TimeUnit.SECONDS)
            .readTimeout(1, TimeUnit.SECONDS)
            .writeTimeout(1, TimeUnit.SECONDS)
            .build()

        val request = Request.Builder()
            .url(url)
            .get()
            .build()
        val response = client.newCall(request).execute()

        response.body?.string()?.let {
            val i = Regex("\"data\":\"(.*?)\"").find(it)
            if (i.toString() != "null") {
                i?.groupValues?.get(1).let {
                    if (!TextUtils.isEmpty(it)) {
                        val str = AESHelper.decrypt(it!!)
                        saveWeatherData(str)
                    }
                }
            }
        }
    }

    private fun saveWeatherData(string: String) {
        AppPreferences.getInstance().put(getTodayStr() + "_weather", string)
    }

    private fun getTodayStr(): String {
        val calendar = Calendar.getInstance()
        val year = calendar[Calendar.YEAR]
        val month = calendar[Calendar.MONTH] + 1
        val day = calendar[Calendar.DAY_OF_MONTH]

        val today =
            year.toString() + "-" + String.format("%02d", month) + "-" + String.format("%02d", day)

        return today;
    }
}