package com.base.datarecovery.fcm;

import android.util.Log;
import com.base.datarecovery.MyApplication;
import java.util.Timer;
import java.util.TimerTask;

public class RecoveryTimerManager {
    private static RecoveryTimerManager instance;
    private Timer taskTimer;
    private boolean isTimerActive;

    private RecoveryTimerManager() {
        // 私有构造方法
    }

    public static synchronized RecoveryTimerManager getInstance() {
        if (instance == null) {
            instance = new RecoveryTimerManager();
        }
        return instance;
    }

    public void scheduleTask(long delay, long period) {
        synchronized (RecoveryTimerManager.class) {
            ensureTimerIsStopped(); // 确保定时器未运行
            taskTimer = new Timer(); // 创建新的 Timer 实例
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    Log.d("glc", "Scheduled task is running");
                    // 确保设备处于交互状态，未锁定，且应用未暂停
                    if (ScreenStatusReceiver.isDeviceInteractive() &&
                            !ScreenStatusReceiver.isSecureLockActive() &&
                            MyApplication.PAUSED_VALUE != 1) {
                        Log.d("glc", "Scheduled task conditions are met");
                        NotificationUtil.INSTANCE.sendNotification(MyApplication.context,"scheduleTask");
                    }
                }
            };
            taskTimer.schedule(task, delay, period); // 调度任务
            isTimerActive = true; // 设置定时器状态为活跃
        }
    }

    private void ensureTimerIsStopped() {
        if (isTimerActive) {
            if (taskTimer != null) {
                taskTimer.cancel();
                taskTimer.purge(); // 清除所有取消的任务
            }
            isTimerActive = false; // 重置定时器状态
        }
    }

    public void stopTaskTimer() {
        synchronized (RecoveryTimerManager.class) {
            ensureTimerIsStopped(); // 停止定时器
        }
    }

    public boolean isTaskTimerActive() {
        return isTimerActive;
    }
}