package com.xty.common.work

import android.app.Application
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import com.xty.common.bracelet.YCBBlueConnectHelper
import com.xty.common.bracelet.YCBManager
import com.xty.common.bracelet.YCBOrder
import com.xty.common.LogUtils
import java.util.concurrent.TimeUnit

/**
 * 后台数据上传 时间间隔为15分钟
 */
object  MyWorkManger {
    var isCancel = false //是否已经关闭服务
    var isOpenWhatchSetting = false//是否已经打开手表数据采集设置
    private var workManager: WorkManager? = null

    fun setMyWork(context: Application, macAddress: String?) {

        if (macAddress.isNullOrEmpty()) {
            LogUtils.d("worker", "mac地址为空  关闭任务 ")
            cancelWork()
        }

        openWhatchSetting()

        //清除后台上传
        if (workManager == null) {
            LogUtils.d("worker", "开启新的workManager ")
            workManager = WorkManager.getInstance(context)
            //15分钟上传一次  在workManager中 周期任务最小的时间间隔是15分钟  源码里面定义的
            var again = PeriodicWorkRequestBuilder<UploadManager>(60, TimeUnit.MINUTES).build()
            workManager!!.enqueueUniquePeriodicWork(
                "upload",
                ExistingPeriodicWorkPolicy.KEEP,
                again
            )
        } else {
            val workInfosForUniqueWork = workManager!!.getWorkInfosForUniqueWork("upload")
            if (workInfosForUniqueWork.isCancelled) {
                LogUtils.d("worker", "再次开启 ")
                var again = PeriodicWorkRequestBuilder<UploadManager>(60, TimeUnit.MINUTES).build()
                workManager!!.enqueueUniquePeriodicWork(
                    "upload",
                    ExistingPeriodicWorkPolicy.KEEP,
                    again
                )
            }
        }
    }

    /**
     * 手表初始信息设置
     */
    private fun openWhatchSetting(){
        if (isOpenWhatchSetting){//设置过就不重复设置了
            return
        }

        if (!YCBBlueConnectHelper.getBlueStatus(false)) {//手表要是没连接不设置
            return
        }

        isOpenWhatchSetting = true
        YCBManager.openStartMeasure() //开启温度采集时间间隔
        YCBManager.languageSetting()
        YCBManager.settting(YCBOrder.TEMP_DATA, 10, 3) //开启体温数据采集
        YCBManager.settting(YCBOrder.PPG_DATA, 60, 10)  //开启PPG数据采集
        YCBManager.setttingPpg(60, 10)  //开启PPG数据采集  再次开启ppg
        YCBManager.settingHeartMonitor()  //心率监测模式设置
    }

    /**
     * 结束后台数据上传
     */
    fun cancelWork(){
        workManager?.let {
            LogUtils.d("worker", "workManager 关闭")
            isCancel=true
            it.cancelUniqueWork("upload")
        }
    }



}