package com.foxx.androidcast.discovery;

/*********************************************************************
 * PinnedReceiversStore.java
 * Created at: Mon 18 May 2026 17:46:19 +0200
 * Updated at: Wed 20 May 2026 15:17:13 +0200 by Anton Afanasyeu <a.afanasieff@gmail.com>
 * Commit: 5d8e82d2e60a21fff3138d2a394ee4e8b4c6dcb8
 * class PinnedReceiversStore
 * Contributors:
 *    - Anton Afanasyeu <a.afanasieff@gmail.com> (2 commits, 97 lines)
 *    - Cursor Agent (project assistant)
 * Digest: SHA256	68ba4c5f3d15599a6be3b3119233919461009f1725133f13f15e63e7f3fd02d8
**********************************************************************/
import android.content.Context;
import android.content.SharedPreferences;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/** Last successful cast targets shown at the top of the sender device list. */
public final class PinnedReceiversStore {
    private static final String PREFS = "androidcast_pinned_receivers";
    private static final String KEY_ENTRIES = "entries";
    private static final int MAX_PINNED = 5;

    private PinnedReceiversStore() {}

    public static void recordSuccess(Context context, DiscoveryManager.DiscoveredDevice device) {
        if (context == null || device == null) {
            return;
        }
        List<DiscoveryManager.DiscoveredDevice> list = load(context);
        String key = device.host + ":" + device.port;
        list.removeIf(d -> (d.host + ":" + d.port).equals(key));
        DiscoveryManager.DiscoveredDevice copy = new DiscoveryManager.DiscoveredDevice(
                device.name, device.host, device.port, device.transport, System.currentTimeMillis(),
                device.videoCodecs, device.audioCodecs, device.placeholderId, device.protoVersion,
                device.pinAuth);
        copy.pinnedRecent = true;
        list.add(0, copy);
        while (list.size() > MAX_PINNED) {
            list.remove(list.size() - 1);
        }
        save(context, list);
    }

    public static List<DiscoveryManager.DiscoveredDevice> load(Context context) {
        List<DiscoveryManager.DiscoveredDevice> out = new ArrayList<>();
        SharedPreferences p = context.getApplicationContext().getSharedPreferences(PREFS, Context.MODE_PRIVATE);
        String raw = p.getString(KEY_ENTRIES, "[]");
        try {
            JSONArray arr = new JSONArray(raw);
            for (int i = 0; i < arr.length(); i++) {
                JSONObject o = arr.getJSONObject(i);
                DiscoveryManager.DiscoveredDevice d = new DiscoveryManager.DiscoveredDevice(
                        o.optString("name", "?"),
                        o.optString("host", ""),
                        o.optInt("port", 0),
                        o.optString("transport", "udp"),
                        o.optLong("last_seen_ms", 0L),
                        o.optInt("video_codecs", 0),
                        o.optInt("audio_codecs", 0),
                        o.optInt("placeholder_id", 0),
                        o.optLong("proto_version", 0L),
                        o.optString("pin_auth", ""));
                d.pinnedRecent = true;
                if (!d.host.isEmpty() && d.port > 0) {
                    out.add(d);
                }
            }
        } catch (Exception ignored) {
        }
        return out;
    }

    private static void save(Context context, List<DiscoveryManager.DiscoveredDevice> list) {
        JSONArray arr = new JSONArray();
        for (DiscoveryManager.DiscoveredDevice d : list) {
            try {
                JSONObject o = new JSONObject();
                o.put("name", d.name);
                o.put("host", d.host);
                o.put("port", d.port);
                o.put("transport", d.transport);
                o.put("last_seen_ms", d.lastSeenMs);
                o.put("video_codecs", d.videoCodecs);
                o.put("audio_codecs", d.audioCodecs);
                o.put("placeholder_id", d.placeholderId);
                o.put("proto_version", d.protoVersion);
                o.put("pin_auth", d.pinAuth);
                arr.put(o);
            } catch (Exception ignored) {
            }
        }
        context.getApplicationContext().getSharedPreferences(PREFS, Context.MODE_PRIVATE)
                .edit().putString(KEY_ENTRIES, arr.toString()).apply();
    }
}
