using System; using System.IO; using System.Text.Json; namespace Bedtimer { public static class State { private sealed class Model { public string? LastLockCycleId { get; set; } public DateTime LastLockUtc { get; set; } } private static string PathJson => System.IO.Path.Combine(Config.Dir, "state.json"); private static readonly object _gate = new(); private static Model Load() { lock (_gate) { Directory.CreateDirectory(Path.GetDirectoryName(PathJson)!); if (!File.Exists(PathJson)) return new Model(); try { return JsonSerializer.Deserialize(File.ReadAllText(PathJson)) ?? new Model(); } catch { return new Model(); } } } private static void Save(Model m) { lock (_gate) { Directory.CreateDirectory(Path.GetDirectoryName(PathJson)!); File.WriteAllText(PathJson, JsonSerializer.Serialize(m, new JsonSerializerOptions { WriteIndented = true })); } } public static bool IsLockedForCycle(string cycleId) { var m = Load(); return string.Equals(m.LastLockCycleId, cycleId, StringComparison.Ordinal); } public static void MarkLocked(string cycleId) { Save(new Model { LastLockCycleId = cycleId, LastLockUtc = DateTime.UtcNow }); } } }