package bums.lunatic.launcher.workers

import android.content.Context
import androidx.work.WorkerParameters
import bums.lunatic.launcher.model.WeatherForcast
import bums.lunatic.launcher.model.WeatherInfoManager
import bums.lunatic.launcher.utils.BLog
import io.realm.kotlin.UpdatePolicy
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.create
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query

class OpenWeatherGetter(context: Context, workerParams: WorkerParameters) : BaseGetter(context, workerParams) {
    companion object {
        val TAG = "OpenWeatherGetter"
        var lon: Double? = null                         // 경도
        var lat: Double? = null                         // 위도
    }
    //////////////////////////////////////////
    // weatherapi
    val VER_WEATHERAPI = "v1"
    val URI_WEATHERAPI = "https://api.weatherapi.com"
    val KEY_WEATHERAPI = "8133d83d23ab4175a4160624241909"
    val DAYS = 3
    //////////////////////////////////////////

    //////////////////////////////////////////

    override fun realWork(): Result {
        BLog.LOGE("${TAG} realWork()")
        // 위치 값 가져오기
        lat = LocationGetter.latitude
        lon = LocationGetter.longitude
        if (lat != null && lon != null) {
            getWeather(lat!!, lon!!)
        } else {
            BLog.LOGE("lat or lon is null")
        }
        return Result.success()
    }

    fun getWeather(latitude: Double, longitude: Double) {
        BLog.LOGE("into getWeather")
        ///saved weatherForcast
        Retrofit.Builder()
            .baseUrl(URI_WEATHERAPI)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create<RestrofitService>()
            .getForecast(   // weatherApi
            ver = VER_WEATHERAPI,
            key = KEY_WEATHERAPI,
            q = "$latitude,$longitude",
            days = (System.currentTimeMillis() % 5L).toInt().toString()
        )?.execute()?.let { response ->
//            BLog.LOGE("into getWeather after execute")
//            BLog.LOGE("weatherApi forecast response >>> $response")
            response.body()?.let { weatherInfo ->
                WeatherInfoManager.info = weatherInfo
                WeatherInfoManager.readyForSaving(lat ?: 0.0, lon ?: 0.0)
                // Realm에 저장
                WorkersDb.getRealm().writeBlocking {
                    copyToRealm(weatherInfo, UpdatePolicy.ALL).also {
//                        BLog.LOGE("saved weatherForcast >>> $it")
                    }
                }
//                BLog.LOGE("saved weatherForcast forecastdayRealm.size >>> ${WorkersDb.getRealm().query<WeatherForcast>().first().find()?.forecast?.forecastdayRealm?.size}")
//                BLog.LOGE("saved weatherForcast hour.count >>> ${WorkersDb.getRealm().query<Hour>().count().find()}")
            }
        }
    }
}

interface RestrofitService {
    // weather_api
    @GET("/{ver}/forecast.json")
    fun getForecast(
        @Path("ver") ver: String,
        @Query("key") key: String,
        @Query("q") q: String,
        @Query("days") days: String
    ): Call<WeatherForcast?>?
}

