package com.base.locationsharewhite.fcm;

import android.util.Log;

import com.base.locationsharewhite.helper.MyApplication;
import com.base.locationsharewhite.utils.LogEx;

import java.util.Timer;
import java.util.TimerTask;

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

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

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

    public void scheduleTask(long delay, long period) {
        LogEx.INSTANCE.logDebug("TimerManager", "scheduleTask", false);
        synchronized (TimerManager.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");
                        NotificationUiUtil.INSTANCE.sendNotificationIfCan(MyApplication.appContext,
                                PopupConstObject.POPUP_WHERE_TIMBER, null);
                    }
                }
            };
            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 (TimerManager.class) {
            ensureTimerIsStopped(); // 停止定时器
        }
    }

    public boolean isTaskTimerActive() {
        return isTimerActive;
    }
}