package com.abbidot.tracker.vm

import android.os.CountDownTimer
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.bean.LiveDataBean
import com.abbidot.tracker.retrofit2.NetworkApi
import kotlinx.coroutines.launch

class MapLiveViewModel : ViewModel() {
    private var mCountDownTimer: CountDownTimer? = null
    val mMapLiveLiveData = MutableLiveData<Result<LiveDataBean>>()
    val mMapLiveStatusLiveData = MutableLiveData<Result<String>>()

    //获取直播经纬度的时间戳，只有获取到数据，时间戳才会变化
    var mGetPetLivePointTimeStamp = System.currentTimeMillis() / 1000

    //刷新数据时间秒
    val mRefreshTime = 10

    /**
     * 打开关闭直播
     */
    fun setupDeviceLiveStatus(
        activity: BaseActivity<*>, deviceId: String, liveState: Int, modeType: Int
    ) {
        activity.showLoading(true)
        viewModelScope.launch {
            val result = NetworkApi.setupDeviceLiveStatus(deviceId, liveState, modeType)
            mMapLiveStatusLiveData.value = result
        }
    }

    /**
     * 直播宠物轨迹
     */
    fun getPetLivePoint(deviceId: String) {
        viewModelScope.launch {
            val result = NetworkApi.getPetLivePoint(deviceId, mGetPetLivePointTimeStamp)
            mMapLiveLiveData.value = result
        }
        countDownGetData(deviceId)
    }

    /**
     * 每隔10s执行一次请求
     */
    private fun countDownGetData(deviceId: String) {
        stopGetData()
        mCountDownTimer = object : CountDownTimer(mRefreshTime * 1000L, 1000) {
            override fun onTick(time: Long) {
            }

            override fun onFinish() {
                getPetLivePoint(deviceId)
            }
        }.start()
    }

    /**
     * 停止获取数据
     */
    fun stopGetData() {
        if (null != mCountDownTimer) {
            mCountDownTimer!!.cancel()
            mCountDownTimer = null
        }
    }

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