package bums.lunatic.launcher.workers

import android.annotation.SuppressLint
import android.content.Context
import android.location.Location
import androidx.work.WorkerParameters
import bums.lunatic.launcher.LauncherActivity.Companion.runWeatherGetter
import bums.lunatic.launcher.helpers.PrefHelper
import bums.lunatic.launcher.helpers.letTrue
import bums.lunatic.launcher.utils.BLog
import bums.lunatic.launcher.workers.LocationUpdateService.Companion.pushLocation
import com.google.android.gms.location.LocationServices
import com.google.android.gms.location.Priority
import com.google.android.gms.tasks.CancellationTokenSource
import kotlin.math.cos

class LocationGetter(context: Context, workerParams: WorkerParameters) : BaseGetter(context, workerParams) {
    companion object {
        val TAG = "LocationGetter"
        var longitude: Double? = null
        var latitude: Double? = null
    }

    @SuppressLint("MissingPermission")
    override fun realWork(): Result {
        BLog.LOGE("${OpenWeatherGetter.TAG} realWork()")

        LocationServices.getFusedLocationProviderClient(this.applicationContext)
            .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}")
                    longitude = it.longitude
                    latitude = it.latitude
                    runWeatherGetter()
                    PrefHelper.isLocationOn().letTrue {
                       pushLocation(this.applicationContext,it.latitude, it.longitude)
                    }
                }
            }.addOnFailureListener{
                BLog.LOGE("Location error >>> $it")
            }

        return Result.success()
    }



}


val EARTH_RADIUS_METERS = 6371000
val LATITUDE_DEGREE_PER_METER: Double = 1.0 / (2 * Math.PI * EARTH_RADIUS_METERS / 360)

fun latitudeRange(latitude: Double, radiusInMeters: Int): DoubleArray {
    val degreeRange = radiusInMeters * LATITUDE_DEGREE_PER_METER

    val minLatitude = latitude - degreeRange
    val maxLatitude = latitude + degreeRange

    return doubleArrayOf(minLatitude, maxLatitude)
}

fun longitudeRange(latitude: Double, longitude: Double, radiusInMeters: Int): DoubleArray {
    val longitudeDegreePerMeter: Double = 360 / (2 * Math.PI * EARTH_RADIUS_METERS * cos(Math.toRadians(latitude)))
    val degreeRange = longitudeDegreePerMeter * radiusInMeters

    val minLongitude = longitude - degreeRange
    val maxLongitude = longitude + degreeRange

    return doubleArrayOf(minLongitude, maxLongitude)
}


//https://jinkpark.tistory.com/296
//https://develoyummer.tistory.com/103
//https://ghj1001020.tistory.com/300