package com.miraclegarden.smsmessage.service;

import android.content.Context;

import androidx.work.ExistingPeriodicWorkPolicy;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkManager;

import com.miraclegarden.smsmessage.KeepAliveSettings;

import java.util.concurrent.TimeUnit;

public final class MonitoredAppKeepAliveScheduler {

    private static final String WORK_NAME = "monitored_app_keep_alive";

    private MonitoredAppKeepAliveScheduler() {
    }

    public static void schedule(Context context) {
        Context appContext = context.getApplicationContext();
        if (!KeepAliveSettings.isEnabled(appContext)) {
            cancel(appContext);
            return;
        }

        int interval = KeepAliveSettings.getIntervalMinutes(appContext);
        if (interval < KeepAliveSettings.WORK_MANAGER_MIN_MINUTES) {
            WorkManager.getInstance(appContext).cancelUniqueWork(WORK_NAME);
            MonitoredAppKeepAliveLoop.start(appContext);
            return;
        }

        MonitoredAppKeepAliveLoop.stop();
        PeriodicWorkRequest request = new PeriodicWorkRequest.Builder(
                MonitoredAppKeepAliveWorker.class, interval, TimeUnit.MINUTES)
                .build();
        WorkManager.getInstance(appContext).enqueueUniquePeriodicWork(
                WORK_NAME,
                ExistingPeriodicWorkPolicy.UPDATE,
                request);
    }

    public static void cancel(Context context) {
        Context appContext = context.getApplicationContext();
        WorkManager.getInstance(appContext).cancelUniqueWork(WORK_NAME);
        MonitoredAppKeepAliveLoop.stop();
    }
}
