package com.base.locationsharewhite.ui.locationmap

import android.annotation.SuppressLint
import android.app.Activity
import android.location.Location
import android.os.Looper
import androidx.lifecycle.LifecycleCoroutineScope
import com.base.locationsharewhite.location.LocationPositionUtils.uploadMyLocation
import com.base.locationsharewhite.map.MapUtils.getLatLngByLocationManager
import com.base.locationsharewhite.utils.BatteryUtils.getBatteryLevel
import com.base.locationsharewhite.utils.LogEx
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationCallback
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationResult
import com.google.android.gms.location.LocationServices
import com.google.android.gms.maps.model.LatLng
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch

class LocationPresenter(
    val activity: Activity,
    val lifecycleCoroutineScope: LifecycleCoroutineScope
) {

    private var TAG = "LocationPresenter"
    private var uploadJob: Job? = null


    //google的地理位置服务
    private var fusedLocationClient: FusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(activity)
    var googleLocation: LatLng? = null

    //一次性更新自己的位置
    var oneShotLocationCallBack: (() -> Unit)? = null

    //刷新自己的位置
    var refreshLocationCallBack: ((latLng: LatLng?) -> Unit)? = null

    fun getMyLocation(): LatLng? {
        var latLng = activity.getLatLngByLocationManager()
        if (latLng == null) {
            latLng = googleLocation
        }
        return latLng
    }

    fun startUploadMyLocation() {
        if (uploadJob == null) {
            uploadJob = lifecycleCoroutineScope.launch(Dispatchers.IO) {
                while (isActive) {
                    getGoogleServiceLocation()

                    val latLng = getMyLocation()

                    val power = activity.getBatteryLevel()
                    latLng?.let {
                        launch(Dispatchers.Main) {
                            refreshLocationCallBack?.invoke(it)
                        }
                        uploadMyLocation(latLng, power)
                    }
                    delay(10 * 1000L)
                }
            }
        }
    }


    @SuppressLint("MissingPermission")
    fun getGoogleServiceLocation() {
        fusedLocationClient.lastLocation
            .addOnSuccessListener { location: Location? ->
                if (location != null) {
                    val latLng = LatLng(location.latitude, location.longitude)
                    googleLocation = latLng

                    oneShotLocationCallBack?.invoke()
                    oneShotLocationCallBack = null

                }
            }.addOnFailureListener { e ->
                LogEx.logDebug(TAG, "e=$e")
            }
    }

    fun cancelUploadJob() {
        uploadJob?.cancel()
        uploadJob = null
    }


    private var locationCallback: LocationCallback? = null

    /**
     * 请求google service地理位置跟新
     */
    @SuppressLint("MissingPermission")
    fun requestLocationUpdates() {

        // 创建LocationRequest对象，并设置参数
        val locationRequest: LocationRequest = LocationRequest.create()
        locationRequest.setInterval(10000) // 设置更新间隔为10秒
        locationRequest.setFastestInterval(5000) // 设置最快更新间隔为5秒
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) // 设置位置请求的优先级

        locationCallback = object : LocationCallback() {
            override fun onLocationResult(locationResult: LocationResult) {
                for (location in locationResult.locations) {
                    // 在这里获取最新的经纬度
                    val latitude = location.latitude
                    val longitude = location.longitude
                }
            }
        }

        locationCallback?.let {
            // 请求位置更新
            fusedLocationClient.requestLocationUpdates(locationRequest, it, Looper.getMainLooper())
        }

    }

    /**
     * 取消google service地理位置更新
     */
    fun cancelLocationUpdates() {
        locationCallback?.let {
            fusedLocationClient.removeLocationUpdates(it)
        }
    }


}