package com.base.filerecoveryrecyclebin.help

import android.annotation.SuppressLint
import android.text.TextUtils
import com.base.filerecoveryrecyclebin.BuildConfig
import com.base.filerecoveryrecyclebin.GlobalConfig
import com.base.filerecoveryrecyclebin.bean.WeatherBean
import com.base.filerecoveryrecyclebin.utils.AESHelper
import com.base.filerecoveryrecyclebin.utils.AppPreferences
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


@SuppressLint("SimpleDateFormat")
object WeatherUtils {
    private val TAG = "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()
        // LogEx.logDebug(TAG, "getWeatherEntity str=$str")
        if (TextUtils.isEmpty(str)) {
        } 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(TAG, "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 {
                    val i = Regex("\"data\":\"(.*?)\"").find(it)
                    if (i.toString() != "null") {
                        i?.groupValues?.get(1).let { data ->
                            // LogEx.logDebug(TAG, "data=$data")
                            if (!TextUtils.isEmpty(data)) {
                                val str = AESHelper.decrypt(data ?: "")
                                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;
    }
}