package rasel.lunar.launcher.workers

import android.annotation.SuppressLint
import android.content.Context
import android.location.Location
import androidx.work.WorkerParameters
import com.google.android.gms.location.LocationServices
import com.google.android.gms.location.Priority
import com.google.android.gms.tasks.CancellationTokenSource
import io.realm.kotlin.UpdatePolicy
import io.realm.kotlin.ext.query
import rasel.lunar.launcher.model.WeatherForcast
import rasel.lunar.launcher.utils.BLog
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"
    }
    //////////////////////////////////////////
    // weatherapi
    val VER_WEATHERAPI = "v1"
    val URI_WEATHERAPI = "https://api.weatherapi.com"
    val KEY_WEATHERAPI = "8133d83d23ab4175a4160624241909"
    val DAYS = 1
    //////////////////////////////////////////
    var lon: Double? = null                         // 경도
    var lat: Double? = null                         // 위도
    //////////////////////////////////////////

    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) {
        Retrofit.Builder()
            .baseUrl(URI_WEATHERAPI)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create<RestrofitService>()
            .getForecast(   // weatherApi
            ver = VER_WEATHERAPI,
            key = KEY_WEATHERAPI,
            q = "$latitude,$longitude",
            days = DAYS.toString()
        )?.execute()?.let { response ->
            BLog.LOGE("weatherApi forecast response >>> $response")
            response.body()?.let { weatherInfo ->
                // Realm에 저장
                WorkersDb.getRealm().writeBlocking {
                    weatherInfo.readyForSaving()
                    copyToRealm(weatherInfo, UpdatePolicy.ALL)
                }
                BLog.LOGE("saved weatherForcast >>> ${WorkersDb.getRealm().query<WeatherForcast>().first().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?>?
}

