package com.miraclegarden.smsmessage.service;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;

import com.miraclegarden.smsmessage.KeepAliveSettings;

import java.util.concurrent.TimeUnit;

/**
 * 间隔 &lt; 15 分钟时用前台服务 Handler 定时（WorkManager 最短 15 分钟）。
 */
public final class MonitoredAppKeepAliveLoop {

    private static final Handler HANDLER = new Handler(Looper.getMainLooper());
    private static Context appContext;

    private static final Runnable TICK = new Runnable() {
        @Override
        public void run() {
            if (appContext == null) {
                return;
            }
            if (!NotificationService.isMonitoringActive(appContext)) {
                stop();
                return;
            }
            if (!KeepAliveSettings.isEnabled(appContext)) {
                stop();
                return;
            }
            if (!usesFastLoop(appContext)) {
                stop();
                return;
            }
            MonitoredAppActivator.activateAllAsync(appContext);
            scheduleNext();
        }
    };

    private MonitoredAppKeepAliveLoop() {
    }

    public static boolean usesFastLoop(Context context) {
        return KeepAliveSettings.isEnabled(context)
                && KeepAliveSettings.getIntervalMinutes(context) < KeepAliveSettings.WORK_MANAGER_MIN_MINUTES;
    }

    public static void start(Context context) {
        if (!usesFastLoop(context)) {
            stop();
            return;
        }
        appContext = context.getApplicationContext();
        HANDLER.removeCallbacks(TICK);
        // 先尽快执行一次，再按间隔循环
        HANDLER.postDelayed(TICK, 3000);
    }

    public static void stop() {
        HANDLER.removeCallbacks(TICK);
        appContext = null;
    }

    public static void restart(Context context) {
        stop();
        start(context);
    }

    private static void scheduleNext() {
        if (appContext == null) {
            return;
        }
        long delayMs = TimeUnit.MINUTES.toMillis(KeepAliveSettings.getIntervalMinutes(appContext));
        HANDLER.postDelayed(TICK, delayMs);
    }
}
