package com.okithaki.autoapp;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

import org.json.JSONObject;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/** Native answer/decline actions for closed-app incoming calls. */
public final class CallActionReceiverR10F42 extends BroadcastReceiver {
    public static final String ACTION_ANSWER = "com.okithaki.autoapp.R10F42_ANSWER_CALL";
    public static final String ACTION_DECLINE = "com.okithaki.autoapp.R10F42_DECLINE_CALL";
    private static final String PREFS = "ok_ithaki_prefs";

    @Override public void onReceive(Context context, Intent intent) {
        if (context == null || intent == null) return;
        final PendingResult pending = goAsync();
        final String action = intent.getAction() == null ? "" : intent.getAction();
        final String sessionId = safe(intent.getStringExtra("session_id"));
        final String roomId = value(intent, "room_id", "ithaki-phone-test");
        final SharedPreferences sp = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE);
        final String deviceId = value(intent, "device_id", sp.getString("ok_fcm_device", ""));
        final String server = value(intent, "server", sp.getString("ok_fcm_server", "https://ok-ithaki.gr"));
        final boolean accepted = ACTION_ANSWER.equals(action);
        cancelCall(context, intent, sessionId);
        sp.edit()
                .putLong("r10f42_last_call_action_at", System.currentTimeMillis())
                .putString("r10f42_last_call_action", accepted ? "answer" : "decline")
                .putString("r10f42_last_call_action_session", sessionId)
                .apply();

        // Answer opens the call screen immediately; the server response is sent in parallel.
        if (accepted) {
            Intent open = new Intent(context, MainActivity.class);
            open.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            copyExtras(intent, open);
            open.putExtra("kind", value(intent, "resolved_kind", value(intent, "kind", "video_call")));
            open.putExtra("call", "1");
            open.putExtra("call_action", "answer");
            open.putExtra("open_video_call_immediately", "1");
            context.startActivity(open);
        }

        new Thread(() -> {
            try {
                postResponse(server, roomId, sessionId, deviceId, accepted);
            } finally {
                try { pending.finish(); } catch (Exception ignored) { }
            }
        }, "ithaki-r10f42-call-action").start();
    }

    private static void postResponse(String server, String roomId, String sessionId, String deviceId, boolean accepted) {
        if (sessionId.isEmpty() || deviceId.isEmpty()) return;
        HttpURLConnection conn = null;
        try {
            URL url = new URL(server.replaceAll("/+$", "") + "/api/video/session/respond");
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(7000);
            conn.setReadTimeout(7000);
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            JSONObject body = new JSONObject();
            body.put("room_id", roomId);
            body.put("session_id", sessionId);
            body.put("device_id", deviceId);
            body.put("accepted", accepted);
            byte[] bytes = body.toString().getBytes(StandardCharsets.UTF_8);
            try (OutputStream os = conn.getOutputStream()) { os.write(bytes); }
            int code = conn.getResponseCode();
            // consume response so the request completes cleanly
            try { if (code >= 200 && code < 400) conn.getInputStream().close(); else if (conn.getErrorStream() != null) conn.getErrorStream().close(); } catch (Exception ignored) { }
        } catch (Exception ignored) {
        } finally {
            try { if (conn != null) conn.disconnect(); } catch (Exception ignored) { }
        }
    }

    private static void cancelCall(Context context, Intent intent, String sessionId) {
        try {
            NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            int id = intent.getIntExtra("notification_id_int", Integer.MIN_VALUE);
            if (id != Integer.MIN_VALUE && nm != null) nm.cancel(id);
            if (nm != null && !sessionId.isEmpty()) nm.cancel(Math.abs(("call_" + sessionId).hashCode()));
        } catch (Exception ignored) { }
    }

    private static void copyExtras(Intent from, Intent to) {
        if (from.getExtras() == null) return;
        for (String k : from.getExtras().keySet()) {
            Object v = from.getExtras().get(k);
            if (v instanceof String) to.putExtra(k, (String) v);
            else if (v instanceof Integer) to.putExtra(k, (Integer) v);
            else if (v instanceof Boolean) to.putExtra(k, (Boolean) v);
            else if (v instanceof Long) to.putExtra(k, (Long) v);
        }
    }

    private static String value(Intent i, String key, String fallback) {
        String v = safe(i.getStringExtra(key));
        return v.isEmpty() ? safe(fallback) : v;
    }

    private static String safe(String s) { return s == null ? "" : s.trim(); }
}
