package com.nadi.player.nativeplayer.lastplayed;

import android.content.Context;
import android.content.SharedPreferences;

import com.nadi.player.nativeplayer.channels.Channel;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Tiny SharedPreferences-backed "last played channel" store.
 *
 * Used to power the JS-side "Resume {name}" toast that the LiveTV page
 * shows on cold start — IPTV users typically rotate between the same
 * 5–10 channels, so jumping straight back into the previous one is a
 * one-tap retention win.
 *
 * We only persist what the JS layer actually needs to re-launch the
 * stream (URL, title, headers/UA, channel number for the overlay
 * highlight). No EPG / no logo URL — those will be refetched anyway.
 */
public final class LastPlayedStore {

    private static final String PREFS = "nadi_player_last_played";
    private static final String KEY_JSON = "last_payload_v1";

    private LastPlayedStore() {}

    /** Persist whatever metadata the activity has for the currently
     *  playing channel. Safe to call on every channel zap — writes are
     *  done via {@code apply()} so they don't block the UI thread. */
    public static void save(Context ctx, String title, String streamUrl,
                            boolean isLive, String userAgent,
                            int channelNumber, String profileId) {
        if (ctx == null || streamUrl == null || streamUrl.isEmpty()) return;
        try {
            JSONObject o = new JSONObject();
            o.put("title", title == null ? "" : title);
            o.put("url", streamUrl);
            o.put("isLive", isLive);
            if (userAgent != null && !userAgent.isEmpty()) o.put("userAgent", userAgent);
            if (channelNumber > 0) o.put("channelNumber", channelNumber);
            if (profileId != null && !profileId.isEmpty()) o.put("profileId", profileId);
            o.put("savedAt", System.currentTimeMillis());
            ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
                    .edit()
                    .putString(KEY_JSON, o.toString())
                    .apply();
        } catch (JSONException ignored) {
            /* never throws for our value types */
        }
    }

    /** Convenience overload used during fast zaps where we already have a
     *  {@link Channel} object. */
    public static void save(Context ctx, Channel ch, boolean isLive,
                            String userAgent, String profileId) {
        if (ch == null) return;
        save(ctx, ch.name, ch.streamUrl, isLive,
                userAgent != null ? userAgent : ch.userAgent,
                ch.number, profileId);
    }

    /** @return raw JSON string, or null if nothing saved. */
    public static String getRawJson(Context ctx) {
        if (ctx == null) return null;
        return ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
                .getString(KEY_JSON, null);
    }

    public static void clear(Context ctx) {
        if (ctx == null) return;
        ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
                .edit().remove(KEY_JSON).apply();
    }
}
