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"
    }
    //////////////////////////////////////////
    // openWeatherMap
    val URI_OPEN_WEATHER_MAP = "https://api.openweathermap.org"
    val KEY_OPEN_WEATHER_MAP = "87cd0810b7e4b4debd31a6ef98b98154"
    // 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                         // 위도
    //////////////////////////////////////////
    @SuppressLint("MissingPermission")
    override fun realWork(): Result {
        BLog.LOGE("${TAG} realWork()  ")
//        setLocation()

        fun location(loc: Location?) {
            val service = Retrofit.Builder()
                .baseUrl(URI_WEATHERAPI)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .run { this.create<RestrofitService>() }
            service.getForecast(
                ver = VER_WEATHERAPI,
                key = KEY_WEATHERAPI,
                q = "${loc?.latitude ?: lat},${loc?.longitude  ?: lon}",
                days = DAYS.toString()
            )?.execute()?.let { response ->
                response.body()?.let { weatherInfo ->
                    BLog.LOGE("Location error >>> $weatherInfo")
                    WorkersDb.getRealm().writeBlocking {
                        weatherInfo.readyForSaving()
                        copyToRealm(weatherInfo, UpdatePolicy.ALL)
                    }
                    BLog.LOGE("saved weatherForcast >>> ${WorkersDb.getRealm().query<WeatherForcast>().first().find()}")
                }
            }
        }

        val fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this.applicationContext)
        fusedLocationProviderClient.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY,CancellationTokenSource().token)
            .addOnSuccessListener{ success: Location? ->
                success?.let {
                    BLog.LOGE("Location >>> $it")
                    BLog.LOGE("Location >>> (latitude)${it.longitude}/(longitude)${it.latitude}")
                    lon = it.longitude
                    lat = it.latitude

                    //{https://home.openweathermap.org/api 에서 정보를 조회 하자}
                    location(null)
                }
            }.addOnFailureListener{
                BLog.LOGE("Location error >>> $it")
            }
//        }

        return Result.success()
    }

    @SuppressLint("MissingPermission")
    fun setLocation() {

    }

    fun getWeather(loc: Location?) {

    }
}

interface RestrofitService {
    // open_weather_map
//    @GET("/data/2.5/weather")
//    fun getPosts(
//        @Query("lat") lat: Double,
//        @Query("lon") lon: Double,
//        @Query("appid") key: String
//    ): Call<WeatherInfo?>?

    // 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?>?
}

