package bums.lunatic.launcher.workers

import android.Manifest
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Geocoder
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Build
import android.os.IBinder
import android.widget.Toast
import androidx.core.app.ActivityCompat
import bums.lunatic.launcher.helpers.PrefHelper
import bums.lunatic.launcher.helpers.PrefString
import bums.lunatic.launcher.helpers.letTrue
import bums.lunatic.launcher.model.LocationLog
import bums.lunatic.launcher.utils.BLog
import com.google.android.gms.location.LocationServices
import com.google.gson.Gson
import io.realm.kotlin.ext.query
import io.realm.kotlin.query.Sort
import okhttp3.ConnectionPool
import okhttp3.MediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.Response
import okhttp3.ResponseBody
import java.io.IOException
import java.util.Base64
import java.util.Locale
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit


class LocationUpdateService : Service(), LocationListener {

    companion object {
        private const val MIN_DISTANCE_CHANGE_FOR_UPDATES: Long = 200
        private const val MIN_TIME_BW_UPDATES: Long = 30

        fun pushLocation(context: Context, lat :Double, long : Double) {
            try {
                val geocoder = Geocoder(context, Locale.getDefault())
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                    geocoder.getFromLocation(lat, long, 1) { addresses ->
                        addresses.first()?.let {
                            WorkersDb.getRealm()?.apply {
                                LocationLog().let { loc ->
                                    loc.fillData(it)
//                                    var list = query<LocationLog>().sort("time", Sort.DESCENDING).find()
//                                    (list.size == 0 || (list.size > 0 && list.first().time < (System.currentTimeMillis() - (1000L * 60L * 10L))  &&  list.first().mLatitude )).letTrue {
                                    Executors.newSingleThreadScheduledExecutor().schedule({
                                        try {
                                            //////-1002450229641
                                            val url = PrefString.locationApi.get()
                                            if (url.length > 10) {
                                                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()
                                                builder.method(
                                                    "POST", RequestBody.create(
                                                        MediaType.parse("application/text"),
                                                        Base64.getEncoder().encode(
                                                            Gson().toJson(this@apply).toByteArray()
                                                        )
                                                    )
                                                )
                                                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)
//                                    }
                                    writeBlocking {
                                        copyToRealm(loc)
                                    }
                                }
                            }
                        }
                        addresses.forEach {  }
                    }
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }
    protected var locationManager: LocationManager? = null
    var checkGPS = false
    var checkNetwork = false

    // boolean canGetLocation = false;
    var loc: Location? = null


    override fun onBind(intent: Intent?): IBinder? {
        TODO("Not yet implemented")
    }

    override fun onLocationChanged(p0: Location) {
        BLog.LOGE("p0")
        PrefHelper.isLocationOn().letTrue {
            pushLocation(this.applicationContext, p0.latitude,p0.longitude)
        }
    }

    override fun onCreate() {
        super.onCreate()
        location
    }


    private val location: Location?
        private get() {
            if (ActivityCompat.checkSelfPermission(
                    this,
                    Manifest.permission.ACCESS_FINE_LOCATION
                ) !=
                PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                    this,
                    Manifest.permission.ACCESS_COARSE_LOCATION
                )
                != PackageManager.PERMISSION_GRANTED
            ) {
            }
            locationManager = applicationContext
                .getSystemService(LOCATION_SERVICE) as LocationManager
            checkGPS = locationManager!!
                .isProviderEnabled(LocationManager.GPS_PROVIDER)
            checkNetwork = locationManager!!
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER)
            locationManager?.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES.toFloat(), this)
            if (locationManager != null) {
                val fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
                fusedLocationClient.lastLocation.addOnSuccessListener { location ->
                    if (location != null) {
                        Toast.makeText(
                            applicationContext,
                            java.lang.Double.toString(location.latitude) + location.longitude + "from method",
                            Toast.LENGTH_LONG
                        ).show()
                        pushLocation(this.applicationContext, location.latitude, location.longitude)
                    }
                }
            }
            return loc
        }





}