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.service.StayJobService
import com.base.locationsharewhite.service.StayJobService.Companion.oneShotLocationCallBack
import com.base.locationsharewhite.service.StayJobService.Companion.requestServiceLocationUpdates
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


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

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

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

                    val latLng = getMyLocation()

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


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

    companion object {

    }

}