package com.base.browserwhite.help

import android.annotation.SuppressLint
import com.base.browserwhite.BuildConfig
import com.base.browserwhite.bean.WeatherBean
import com.base.browserwhite.bean.WeatherCityBean
import com.base.browserwhite.utils.LogEx
import com.google.gson.Gson
import com.google.gson.JsonParser
import com.google.gson.reflect.TypeToken
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.logging.HttpLoggingInterceptor
import java.lang.reflect.Type
import java.text.SimpleDateFormat
import java.util.concurrent.TimeUnit

@SuppressLint("SimpleDateFormat")
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()
    }

}