package com.base.locationsharewhite.ui.main

import android.annotation.SuppressLint
import android.app.Activity
import android.location.Location
import android.os.Looper
import androidx.lifecycle.LifecycleCoroutineScope
import com.base.locationsharewhite.map.MapUtils.getLatLngByLocationManager
import com.base.locationsharewhite.service.StayJobService
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 MainPresenter(
    val activity: Activity
) {

    private val TAG = "MainPresenter"


    /**
     * 获取自身位置,
     */
    private fun getMyLocation(): LatLng? {
        var latLng = activity.getLatLngByLocationManager()
        LogEx.logDebug(TAG, "getMyLocation latLng=$latLng")
        if (latLng == null) {
            latLng = StayJobService.googleLocation
        }
        return latLng
    }

    var uiLocationCallback: ((latLng: LatLng) -> Unit)? = null

    private var locationJob: Job? = null

    fun startLocationJob(lifecycleCoroutineScope: LifecycleCoroutineScope) {
        if (locationJob == null) {
            locationJob = lifecycleCoroutineScope.launch(Dispatchers.IO) {

                while (isActive) {
                    val latLng = getMyLocation()

                    launch(Dispatchers.Main) {
                        latLng?.let { uiLocationCallback?.invoke(it) }
                    }

                    delay(10 * 1000L)
                }

            }
        }
    }

    fun cancelLocationJob() {
        locationJob?.cancel()
        locationJob = null
    }
}