#nullable enable using System; using System.IO; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using ReminderOrganizer.Models; namespace ReminderOrganizer.Services { /// /// Stores tasks in %APPDATA%\ReminderOrganizer\tasks.json. /// Writes are serialized and atomic (temp file + replace), a corrupt file is /// backed up instead of being overwritten. /// public class DataService : IDataService { private static readonly JsonSerializerOptions _jsonOptions = new() { WriteIndented = true, PropertyNameCaseInsensitive = true }; private readonly SemaphoreSlim _writeLock = new(1, 1); public string DataFilePath { get; } /// %APPDATA%\ReminderOrganizer – or REMINDER_ORGANIZER_DATA (for tests/screenshots). public static string DefaultDataDirectory => Environment.GetEnvironmentVariable("REMINDER_ORGANIZER_DATA") is { Length: > 0 } custom ? custom : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ReminderOrganizer"); public DataService() : this(DefaultDataDirectory) { } public DataService(string dataDirectory) { Directory.CreateDirectory(dataDirectory); DataFilePath = Path.Combine(dataDirectory, "tasks.json"); } /// Copies tasks.json from an old location (next to the exe) if no data exists yet. public void MigrateFrom(string? legacyDirectory) { if (string.IsNullOrEmpty(legacyDirectory) || File.Exists(DataFilePath)) return; var legacy = Path.Combine(legacyDirectory, "tasks.json"); try { if (File.Exists(legacy) && !string.Equals(Path.GetFullPath(legacy), Path.GetFullPath(DataFilePath), StringComparison.OrdinalIgnoreCase)) File.Copy(legacy, DataFilePath); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"[DataService] Migration failed: {ex.Message}"); } } public async Task LoadAsync() { if (!File.Exists(DataFilePath)) return new AppData(); try { var json = await File.ReadAllTextAsync(DataFilePath); var data = JsonSerializer.Deserialize(json, _jsonOptions); return data ?? new AppData(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"[DataService] Load failed: {ex.Message}"); BackupCorruptFile(); return new AppData(); } } private void BackupCorruptFile() { try { var backup = DataFilePath + $".corrupt-{DateTime.Now:yyyyMMdd-HHmmss}"; File.Copy(DataFilePath, backup, overwrite: true); } catch { } } public void Save(AppData data) { _writeLock.Wait(); try { var tmp = DataFilePath + ".tmp"; File.WriteAllText(tmp, JsonSerializer.Serialize(data, _jsonOptions)); Commit(tmp); } finally { _writeLock.Release(); } } private void Commit(string tmp) { if (File.Exists(DataFilePath)) File.Replace(tmp, DataFilePath, DataFilePath + ".bak"); else File.Move(tmp, DataFilePath); } public async Task SaveAsync(AppData data) { await _writeLock.WaitAsync(); try { var json = JsonSerializer.Serialize(data, _jsonOptions); var tmp = DataFilePath + ".tmp"; await File.WriteAllTextAsync(tmp, json); Commit(tmp); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"[DataService] Save failed: {ex.Message}"); throw; } finally { _writeLock.Release(); } } } }