package io.kiotplugins.kioskplugin;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

public class WatchdogService extends Service {
    private Handler handler = new Handler();
    private int tries = 0;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // Start as foreground service with notification
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelId = "kiosk_watchdog";
            NotificationChannel channel = new NotificationChannel(
                    channelId,
                    "Kiosk Watchdog Service",
                    NotificationManager.IMPORTANCE_LOW);
            NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            manager.createNotificationChannel(channel);

            Notification notification = new Notification.Builder(this, channelId)
                    .setContentTitle("Watchdog Service Running")
                    .setContentText("Home Console is protected")
                    .setSmallIcon(android.R.drawable.ic_lock_lock)
                    .build();

            startForeground(1, notification);
        } else {
            Notification notification = new Notification.Builder(this)
                    .setContentTitle("Watchdog Service Running")
                    .setContentText("Home Console is protected")
                    .setSmallIcon(android.R.drawable.ic_lock_lock)
                    .build();
            startForeground(1, notification);
        }
        
        handler.post(checkRunnable);
        return START_STICKY;
    }

    private Runnable checkRunnable = new Runnable() {
        @Override
        public void run() {
            tries++;
            try {
                Intent launchIntent = getPackageManager().getLaunchIntentForPackage(getPackageName());
                if (launchIntent != null) {
                    launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(launchIntent);
                    Log.d("KioskWatchdogService", "Launching activity (attempt #" + tries + ")");
                }
            } catch (Exception e) {
                Log.e("KioskWatchdogService", "Watchdog failed: " + e.getMessage());
            }
            if (tries < 20) { // ~60s, try every 3s
                handler.postDelayed(this, 3000);
            } else {
                stopSelf();
            }
        }
    };

    @Override
    public void onDestroy() {
        handler.removeCallbacks(checkRunnable);
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) { return null; }
}
