package com.base.locationsharewhite.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.locationsharewhite.fcm.NotificationUiUtil.sendNotificationIfCan
import com.base.locationsharewhite.fcm.PopupConstObject
import com.base.locationsharewhite.helper.EventUtils
import java.util.concurrent.TimeUnit

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

    override fun doWork(): Result {
        // 这里执行你的任务
        // 例如，更新UI，发送网络请求等
        EventUtils.event("workmanager_live")
        try {
            sendNotificationIfCan(appContext, PopupConstObject.POPUP_WHERE_WORK_MANAGER);
        } catch (e: Exception) {
            EventUtils.event("WorkManager Error")
        }
        return Result.success()
    }

    companion object {
        const val TAG = "uniqueWorkName"

        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
            )
        }

    }
}