package com.base.locationsharewhite.ui.locationmap

import android.content.Context
import androidx.lifecycle.LifecycleCoroutineScope
import com.base.locationsharewhite.location.LocationPositionUtils
import com.base.locationsharewhite.location.LocationPositionUtils.uploadMyLocation
import com.base.locationsharewhite.map.MapUtils.getLastKnowLatLng
import com.base.locationsharewhite.utils.BatteryUtils.getBatteryLevel
import com.base.locationsharewhite.utils.LogEx
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch

class LocationPresenter(
    val context: Context,
    val lifecycleCoroutineScope: LifecycleCoroutineScope
) {
    private var TAG = "LocationPresenter"
    private var uploadJob: Job? = null

    fun startUploadMyLocation() {
        if (uploadJob == null) {
            LogEx.logDebug(TAG,"startUploadMyLocation")
            uploadJob = lifecycleCoroutineScope.launch(Dispatchers.IO) {
                while (isActive) {
                    val latLng = context.getLastKnowLatLng()
                    val power = context.getBatteryLevel()
                    uploadMyLocation(latLng, power)
                    delay(30 * 1000L)
                }
            }
        }
    }

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

}