package com.base.browserwhite.fcm;

import static com.base.browserwhite.fcm.NotificationPushUtil.PUSH_WHERE_TIMBER;

import android.Manifest;
import android.app.Notification;
import android.content.pm.PackageManager;
import android.util.Log;

import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationManagerCompat;

import com.base.browserwhite.MyApplication;
import com.base.browserwhite.service.StayNotificationService;

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

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

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

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

    public void scheduleTask(long delay, long period) {
        synchronized (NotificationTimerManager.class) {
            ensureTimerIsStopped(); // 确保定时器未运行
            taskTimer = new Timer(); // 创建新的 Timer 实例
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    Notification notification = StayNotificationService.Companion.createPermanentNotification(MyApplication.context);
                    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(MyApplication.context);
                    if (ActivityCompat.checkSelfPermission(MyApplication.context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
                    }else {
                        notificationManager.notify(100, notification);
                    }
                }
            };
            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 (NotificationTimerManager.class) {
            ensureTimerIsStopped(); // 停止定时器
        }
    }

    public boolean isTaskTimerActive() {
        return isTimerActive;
    }
}