package com.base.scanqr.fcm.work

import android.content.Context
import androidx.work.Constraints
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.base.scanqr.bean.NotificationSendBean
import com.base.scanqr.bean.NotificationSendBean.Companion.POPUP_WHERE_WORK_MANAGER
import com.base.scanqr.fcm.notification.MyNotificationManager
import com.base.scanqr.helper.EventUtils
import com.base.scanqr.utils.LogEx
import java.util.concurrent.TimeUnit

class RepeatingWorker(val appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams) {

    override fun doWork(): Result {
        LogEx.logDebug(TAG, "doWork")
        // 这里执行你的任务
        // 例如，更新UI，发送网络请求等
        EventUtils.event("workManager_live")
        try {
            val sendBean = NotificationSendBean(appContext, POPUP_WHERE_WORK_MANAGER, canSend = { true }, sendSuccess = {})
            MyNotificationManager.submitSendBean(sendBean)
        } catch (e: Exception) {
            EventUtils.event("WorkManager Error")
        }
        return Result.success()
    }

    companion object {
        const val TAG = "RepeatingWorker"

        fun schedulePeriodicWork(context: Context) {
            WorkManager.getInstance(context).cancelAllWorkByTag(TAG)

            val request = PeriodicWorkRequestBuilder<RepeatingWorker>(15, TimeUnit.MINUTES)
                .setConstraints(
                    Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()
                )
                .build()

            WorkManager.getInstance(context).enqueueUniquePeriodicWork(
                TAG, ExistingPeriodicWorkPolicy.KEEP, request
            )
        }

    }
}