package com.base.datarecovery.fcm;

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

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


import com.base.datarecovery.MyApplication;
import com.base.datarecovery.help.BaseApplication;
import com.base.datarecovery.service.StayNotificationService;

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

public class NotificationTimerManager {
    private static NotificationTimerManager instance;
    private Timer timer;
    private boolean isTimerRunning;
    private TimerTask timerTask;

    private NotificationTimerManager() {
        isTimerRunning = false;
    }

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

    public void startTimer(long initialDelay, long intervalPeriod) {
        synchronized (this) { // 使用 synchronized 确保线程安全
            if (!isTimerRunning) {
                cancelExistingTimer(); // 取消现有的定时器和任务
                // 创建新的 TimerTask 实例并调度
                timer = new Timer();
                timerTask = 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) {
                            return;
                        }
                        notificationManager.notify(1, notification);
                    }
                };
                timer.schedule(timerTask, initialDelay, intervalPeriod);
                isTimerRunning = true;
            }
        }
    }

    public void stopTimer() {
        synchronized (this) { // 使用 synchronized 确保线程安全
            if (isTimerRunning) {
                cancelExistingTimer();
                isTimerRunning = false;
            }
        }
    }

    private void cancelExistingTimer() {
        if (timerTask != null) {
            timerTask.cancel();
        }
        if (timer != null) {
            timer.cancel();
            timer.purge();
        }
    }

    public boolean isTimerRunning() {
        return isTimerRunning;
    }
}