package io.kiotplugins.kioskplugin;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ServiceInfo;
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;
    private boolean isPaused = false;
    private BroadcastReceiver updateReceiver;
    
    // Intent actions for communication with APKUpdater
    public static final String ACTION_PAUSE_WATCHDOG = "io.kiotplugins.PAUSE_WATCHDOG";
    public static final String ACTION_RESUME_WATCHDOG = "io.kiotplugins.RESUME_WATCHDOG";
    
    // SharedPreferences key for persistent pause state
    private static final String PREF_NAME = "watchdog_prefs";
    private static final String PREF_PAUSED = "is_paused";

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!isWatchdogEnabled()) {
           Log.w("KioskWatchdogService", "Watchdog is not enabled for this app - stopping service");
           stopSelf();
           return START_NOT_STICKY;
        }
        // Check if we should start in paused state (from previous APK update)
        SharedPreferences prefs = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        isPaused = prefs.getBoolean(PREF_PAUSED, false);
        
        // Register broadcast receiver for pause/resume commands
        if (updateReceiver == null) {
            updateReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();
                    if (ACTION_PAUSE_WATCHDOG.equals(action)) {
                        pauseWatchdog();
                    } else if (ACTION_RESUME_WATCHDOG.equals(action)) {
                        resumeWatchdog();
                    }
                }
            };
            
            IntentFilter filter = new IntentFilter();
            filter.addAction(ACTION_PAUSE_WATCHDOG);
            filter.addAction(ACTION_RESUME_WATCHDOG);
            registerReceiver(updateReceiver, filter);
        }
        // For Android 14+ (API 34+), we need to handle foreground services differently
        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.Builder builder = new Notification.Builder(this, channelId)
                    .setContentTitle("Watchdog Service Running")
                    .setContentText("Home Console is protected")
                    .setSmallIcon(android.R.drawable.ic_lock_lock);

            // Try to start as foreground service, but handle potential failures gracefully
            try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
                    // For Android 14+, use systemExempted foreground service type
                    startForeground(1, builder.build(), ServiceInfo.FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED);
                } else {
                    startForeground(1, builder.build());
                }
            } catch (SecurityException e) {
                Log.w("KioskWatchdogService", "Could not start as foreground service: " + e.getMessage());
                // Continue as background service if foreground fails
            }
        } else {
            try {
                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);
            } catch (SecurityException e) {
                Log.w("KioskWatchdogService", "Could not start as foreground service: " + e.getMessage());
            }
        }
        
        if (!isPaused) {
            handler.post(checkRunnable);
        } else {
            Log.d("KioskWatchdogService", "Starting in paused state due to ongoing APK update");
        }
        return START_STICKY;
    }

    // 🔍 HELPER METHOD: Check if watchdog should be enabled
    private boolean isWatchdogEnabled() {
       // Method 1: Check package name
       String packageName = getPackageName();
       if ("io.homeconsole".equals(packageName)) {
           return true;
        }
        // Default: disable if we can't determine
        Log.w("KioskWatchdogService", "Watchdog not explicitly enabled for package: " + packageName);
        return false;
    }

    private Runnable checkRunnable = new Runnable() {
        @Override
        public void run() {
            if (isPaused) {
                Log.d("KioskWatchdogService", "Watchdog is paused, skipping check");
                // Schedule next check in case we get resumed
                handler.postDelayed(this, 3000);
                return;
            }
            
            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();
            }
        }
    };
    
    private void pauseWatchdog() {
        Log.d("KioskWatchdogService", "Pausing watchdog for APK update");
        isPaused = true;
        handler.removeCallbacks(checkRunnable);
        
        // Persist pause state
        SharedPreferences prefs = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        prefs.edit().putBoolean(PREF_PAUSED, true).apply();
        
        // Update notification
        updateNotification("Watchdog Paused", "APK update in progress");
    }
    
    private void resumeWatchdog() {
        Log.d("KioskWatchdogService", "Resuming watchdog after APK update");
        isPaused = false;
        tries = 0; // Reset tries counter
        
        // Clear pause state
        SharedPreferences prefs = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        prefs.edit().putBoolean(PREF_PAUSED, false).apply();
        
        // Update notification
        updateNotification("Watchdog Service Running", "Home Console is protected");
        
        // Restart watchdog checks
        handler.post(checkRunnable);
    }
    
    private void updateNotification(String title, String text) {
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelId = "kiosk_watchdog";
            Notification.Builder builder = new Notification.Builder(this, channelId)
                    .setContentTitle(title)
                    .setContentText(text)
                    .setSmallIcon(android.R.drawable.ic_lock_lock);
            
            try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
                    startForeground(1, builder.build(), ServiceInfo.FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED);
                } else {
                    startForeground(1, builder.build());
                }
            } catch (SecurityException e) {
                Log.w("KioskWatchdogService", "Could not update foreground service: " + e.getMessage());
            }
        } else {
            try {
                Notification notification = new Notification.Builder(this)
                        .setContentTitle(title)
                        .setContentText(text)
                        .setSmallIcon(android.R.drawable.ic_lock_lock)
                        .build();
                startForeground(1, notification);
            } catch (SecurityException e) {
                Log.w("KioskWatchdogService", "Could not update foreground service: " + e.getMessage());
            }
        }
    }

    @Override
    public void onDestroy() {
        handler.removeCallbacks(checkRunnable);
        if (updateReceiver != null) {
            unregisterReceiver(updateReceiver);
            updateReceiver = null;
        }
        super.onDestroy();
    }
    
    // Static helper methods for external classes to control watchdog
    public static void pauseWatchdog(Context context) {
        Intent intent = new Intent(ACTION_PAUSE_WATCHDOG);
        context.sendBroadcast(intent);
    }
    
    public static void resumeWatchdog(Context context) {
        Intent intent = new Intent(ACTION_RESUME_WATCHDOG);
        context.sendBroadcast(intent);
    }

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