package com.abbidot.tracker.vm

import android.annotation.SuppressLint
import android.content.Context
import android.location.Location
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.tracker.util.LonAndLatUtil
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import com.google.android.gms.location.Priority
import com.google.android.gms.tasks.CancellationTokenSource
import com.google.android.gms.tasks.Task

/**
 *Created  by .yzq on 2025/10/16/周四.
 * @link
 * @description:
 */
class GoogleLocationViewModel : ViewModel() {

    val mGoogleLocationLiveData = MutableLiveData<Location>()

    // The Fused Location Provider provides access to location APIs.
    private var mFusedLocationClient: FusedLocationProviderClient? = null
    private var mCancellationTokenSource: CancellationTokenSource? = null


    /**
     * 获取最后位置,用户当前的位置
     */
    @SuppressLint("MissingPermission")
    fun getLastLocation(context: Context) {
        if (null == mFusedLocationClient) {
            mFusedLocationClient = LocationServices.getFusedLocationProviderClient(context)
        }
        mFusedLocationClient!!.lastLocation.addOnCompleteListener { taskLocation ->
            var location: Location? = null
            if (taskLocation.isSuccessful && taskLocation.result != null) {
                location = taskLocation.result
                LonAndLatUtil.currentUserGPSLat = location.latitude
                LonAndLatUtil.currentUserGPSLon = location.longitude
                LogUtil.e("Google,getLastLocation：${location.latitude}, ${location.longitude}")
            } else {
                LogUtil.e("Google,getLastLocation:exception" + taskLocation.exception)
            }
            location?.let {
                mGoogleLocationLiveData.value = it
            }
            if (null == location) requestCurrentLocation(context)
        }

    }

    /**
     * 请求用户当前的位置
     */
    @SuppressLint("MissingPermission")
    private fun requestCurrentLocation(context: Context) {
        try {
            if (null == mFusedLocationClient) {
                mFusedLocationClient = LocationServices.getFusedLocationProviderClient(context)
            }
            if (null == mCancellationTokenSource) {
                mCancellationTokenSource = CancellationTokenSource()
            }
//        val currentLocationTask = mFusedLocationClient.getCurrentLocation(
//            LocationRequest.PRIORITY_HIGH_ACCURACY, mCancellationTokenSource!!.token
//        )
            val currentLocationTask = mFusedLocationClient!!.getCurrentLocation(
                Priority.PRIORITY_HIGH_ACCURACY, mCancellationTokenSource!!.token
            )
            currentLocationTask.addOnCompleteListener { task: Task<Location> ->
                var location: Location? = null
                val result = if (task.isSuccessful && task.result != null) {
                    location = task.result
                    LonAndLatUtil.currentUserGPSLat = location.latitude
                    LonAndLatUtil.currentUserGPSLon = location.longitude
                    "(success): ${location.latitude}, ${location.longitude}"
                } else {
                    val exception = task.exception
                    "(failure): $exception"
                }

                LogUtil.e("Google,requestCurrentLocation $result")
                location?.let {
                    mGoogleLocationLiveData.value = it
                }
            }
        } catch (e: Exception) {
            LogUtil.e("Google,requestCurrentLocation异常:${e.message}")
        }
    }

    private fun stopLocation() {
        mCancellationTokenSource?.cancel()
    }

    override fun onCleared() {
        super.onCleared()
        stopLocation()
    }
}