package com.miraclegarden.smsmessage.mmp;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import org.json.JSONObject;

/**
 * 领取台本地设置（不依赖电脑调试台也能读写）。
 */
public final class MmpLocalSettings {

    private static final String PREF = "mmp_settings_local";

    private MmpLocalSettings() {
    }

    public static JSONObject defaults() {
        JSONObject o = new JSONObject();
        try {
            o.put("historyCooldownSec", 8);
            o.put("detailCooldownSec", 8);
            o.put("dedupSec", 3);
            o.put("detailGapMs", 80);
            o.put("pagePollMs", 1000);
            o.put("openHistoryIfNoTemplate", true);
            o.put("autoBounceHistoryOnDisconnect", true);
            o.put("autoLaunchTngIfKilled", true);
            o.put("autoWatchWhileOpen", true);
        } catch (Exception ignored) {
        }
        return o;
    }

    public static JSONObject load(Context context) {
        JSONObject out = defaults();
        if (context == null) {
            return out;
        }
        SharedPreferences sp = prefs(context);
        try {
            String raw = sp.getString("json", null);
            if (!TextUtils.isEmpty(raw)) {
                JSONObject saved = new JSONObject(raw);
                mergeInto(out, saved);
            }
        } catch (Exception ignored) {
        }
        return out;
    }

    public static void save(Context context, JSONObject json) {
        if (context == null || json == null) {
            return;
        }
        JSONObject merged = defaults();
        mergeInto(merged, json);
        prefs(context).edit().putString("json", merged.toString()).apply();
    }

    public static void mergeInto(JSONObject target, JSONObject src) {
        if (target == null || src == null) {
            return;
        }
        String[] keys = {
                "historyCooldownSec", "detailCooldownSec", "dedupSec", "detailGapMs", "pagePollMs",
                "openHistoryIfNoTemplate", "autoBounceHistoryOnDisconnect",
                "autoLaunchTngIfKilled", "autoWatchWhileOpen"
        };
        for (String k : keys) {
            if (!src.has(k)) {
                continue;
            }
            try {
                target.put(k, src.get(k));
            } catch (Exception ignored) {
            }
        }
    }

    private static SharedPreferences prefs(Context context) {
        return context.getApplicationContext().getSharedPreferences(PREF, Context.MODE_PRIVATE);
    }
}
