package com.cctv.kioskboot;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;

import java.io.DataOutputStream;

public class CctvBootService extends Service {

    private static final String TAG = "CctvBootService";
    private static final String CH = "cctv_kiosk_boot";

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startForeground(1, buildNotification());
        new Handler(Looper.getMainLooper()).postDelayed(this::launchKiosk, 5000);
        return START_STICKY;
    }

    private void launchKiosk() {
        String cmd = "pgrep -f /data/local/tmp/boot-kiosk.sh >/dev/null 2>&1 || " +
            "nohup sh /data/local/tmp/boot-kiosk.sh >> /data/local/tmp/cctv-kiosk.log 2>&1 &";
        boolean ok = runSu(cmd) || runSh(cmd);
        Log.i(TAG, ok ? "Kiosco solicitado" : "Fallo al solicitar kiosco");
        stopForeground(true);
        stopSelf();
    }

    private boolean runSu(String cmd) {
        try {
            Process p = Runtime.getRuntime().exec("su");
            DataOutputStream os = new DataOutputStream(p.getOutputStream());
            os.writeBytes(cmd + "\n");
            os.writeBytes("exit\n");
            os.flush();
            os.close();
            return p.waitFor() == 0;
        } catch (Exception e) {
            Log.w(TAG, "su: " + e.getMessage());
            return false;
        }
    }

    private boolean runSh(String cmd) {
        try {
            Process p = Runtime.getRuntime().exec(new String[]{"/system/bin/sh", "-c", cmd});
            return p.waitFor() == 0;
        } catch (Exception e) {
            Log.w(TAG, "sh: " + e.getMessage());
            return false;
        }
    }

    private Notification buildNotification() {
        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel ch = new NotificationChannel(CH, "CCTV Kiosk", NotificationManager.IMPORTANCE_MIN);
            nm.createNotificationChannel(ch);
        }
        Notification.Builder b = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
            ? new Notification.Builder(this, CH)
            : new Notification.Builder(this);
        return b.setContentTitle("CCTV Kiosk")
            .setContentText("Iniciando mosaico...")
            .setSmallIcon(android.R.drawable.ic_menu_view)
            .build();
    }

    @Override
    public IBinder onBind(Intent intent) { return null; }
}
