using System; using System.Collections.Generic; using UnityEngine; namespace BrewMonster.Scripts { public static class DebugCmdHistoryStore { private const string PlayerPrefsKey = "DebugCmdHistory_v1"; private const int MaxEntries = 200; [Serializable] public class Entry { public int header; public int param; public bool hasParam; public string describe; public long lastUsedUtcTicks; public string KeyString => hasParam ? $"{header}:{param}" : $"{header}:"; } [Serializable] private class EntryListWrapper { public List items = new List(); } public static List Load() { string json = PlayerPrefs.GetString(PlayerPrefsKey, string.Empty); if (string.IsNullOrWhiteSpace(json)) return new List(); try { var wrapper = JsonUtility.FromJson(json); if (wrapper == null || wrapper.items == null) return new List(); wrapper.items.RemoveAll(e => e == null); return wrapper.items; } catch { return new List(); } } public static void Save(List entries) { var wrapper = new EntryListWrapper { items = entries ?? new List() }; string json = JsonUtility.ToJson(wrapper); PlayerPrefs.SetString(PlayerPrefsKey, json); PlayerPrefs.Save(); } public static bool Upsert(List entries, int header, int param, bool hasParam, string describe) { if (entries == null) throw new ArgumentNullException(nameof(entries)); describe = (describe ?? string.Empty).Trim(); int idx = FindIndex(entries, header, param, hasParam); if (idx >= 0) { var e = entries[idx]; bool changed = false; // Overwrite describe whenever it differs (supports updating from empty -> non-empty). if (!string.Equals((e.describe ?? string.Empty).Trim(), describe, StringComparison.Ordinal)) { e.describe = describe; changed = true; } e.lastUsedUtcTicks = DateTime.UtcNow.Ticks; if (idx != 0) { entries.RemoveAt(idx); entries.Insert(0, e); changed = true; } else if (!changed) { // still considered "used"; keep order } return changed; } else { var e = new Entry { header = header, param = param, hasParam = hasParam, describe = describe, lastUsedUtcTicks = DateTime.UtcNow.Ticks }; entries.Insert(0, e); if (entries.Count > MaxEntries) entries.RemoveRange(MaxEntries, entries.Count - MaxEntries); return true; } } public static void Clear() { PlayerPrefs.DeleteKey(PlayerPrefsKey); PlayerPrefs.Save(); } public static bool Remove(List entries, int header, int param, bool hasParam) { if (entries == null) throw new ArgumentNullException(nameof(entries)); int idx = FindIndex(entries, header, param, hasParam); if (idx < 0) return false; entries.RemoveAt(idx); return true; } private static int FindIndex(List entries, int header, int param, bool hasParam) { for (int i = 0; i < entries.Count; i++) { var e = entries[i]; if (e == null) continue; if (e.header != header) continue; if (e.hasParam != hasParam) continue; if (hasParam && e.param != param) continue; return i; } return -1; } } }