using System.Text.Json; using TBDel.Models; namespace TBDel.Services { public class DbService { private readonly string _dbPath; private List _fileCollection; private List _folderCollection; public DbService() { _dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "TBDel_Db.json"); LoadData(); } private void LoadData() { if (File.Exists(_dbPath)) { var json = File.ReadAllText(_dbPath); var dbContent = JsonSerializer.Deserialize(json, JsonContext.Default.DatabaseContent) ?? new DatabaseContent(); _fileCollection = dbContent.FileEntries; _folderCollection = dbContent.FolderEntries; } else { _fileCollection = new List(); _folderCollection = new List(); } } private void SaveData() { var dbContent = new DatabaseContent { FileEntries = _fileCollection, FolderEntries = _folderCollection }; var json = JsonSerializer.Serialize(dbContent, JsonContext.Default.DatabaseContent); File.WriteAllText(_dbPath, json); } public async Task AddFileEntryAsync(FileEntry entry) { _fileCollection.Add(entry); SaveData(); return await Task.FromResult(true); } public async Task AddFolderEntryAsync(FolderEntry entry) { _folderCollection.Add(entry); SaveData(); return await Task.FromResult(true); } public async Task> GetFileEntriesAsync() { return await Task.FromResult(_fileCollection.ToList()); } public async Task> GetFolderEntriesAsync() { return await Task.FromResult(_folderCollection.ToList()); } public async Task RemoveFileEntryAsync(uint id) { var entryToRemove = _fileCollection.FirstOrDefault(e => e.Id == id); if (entryToRemove != null) { _fileCollection.Remove(entryToRemove); SaveData(); return await Task.FromResult(true); } return await Task.FromResult(false); } public async Task RemoveFolderEntryAsync(uint id) { var entryToRemove = _folderCollection.FirstOrDefault(e => e.Id == id); if (entryToRemove != null) { _folderCollection.Remove(entryToRemove); SaveData(); return await Task.FromResult(true); } return await Task.FromResult(false); } } public class DatabaseContent { public DatabaseContent() { FileEntries = new List(); FolderEntries = new List(); } public List FileEntries { get; set; } public List FolderEntries { get; set; } } }