using LiteDB; using VideoStudy.Shared; namespace VideoStudy.UI.Services; public class PersistenceService { private readonly string _basePath; private readonly string _dbPath; public PersistenceService() { _basePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "MeuVideoStudy"); _dbPath = Path.Combine(_basePath, "videostudy.db"); if (!Directory.Exists(_basePath)) { Directory.CreateDirectory(_basePath); } } public string GetBasePath() => _basePath; public List GetFolders() { return Directory.GetDirectories(_basePath) .Select(Path.GetFileName) .Where(name => name != null) .ToList()!; } public void CreateFolder(string folderName) { var path = Path.Combine(_basePath, folderName); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } } public void RenameFolder(string oldName, string newName) { var oldPath = Path.Combine(_basePath, oldName); var newPath = Path.Combine(_basePath, newName); if (Directory.Exists(oldPath) && !Directory.Exists(newPath)) { Directory.Move(oldPath, newPath); } } public async Task SaveSessionAsync(byte[] pdfData, string title, string? youtubeId, string folderName = "Geral") { var folderPath = Path.Combine(_basePath, folderName); if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } var safeTitle = string.Join("_", title.Split(Path.GetInvalidFileNameChars())); var fileName = $"{safeTitle}_{DateTime.Now:yyyyMMdd_HHmmss}.pdf"; var filePath = Path.Combine(folderPath, fileName); await File.WriteAllBytesAsync(filePath, pdfData); using var db = new LiteDatabase(_dbPath); var collection = db.GetCollection("sessions"); var session = new VideoStudySession { Title = title, YouTubeId = youtubeId ?? "local", FilePath = filePath, FolderName = folderName, CreatedAt = DateTime.Now }; collection.Insert(session); collection.EnsureIndex(x => x.Title); return session; } public List GetAllSessions() { using var db = new LiteDatabase(_dbPath); return db.GetCollection("sessions") .FindAll() .OrderByDescending(x => x.CreatedAt) .ToList(); } public List GetSessionsByFolder(string folderName) { using var db = new LiteDatabase(_dbPath); return db.GetCollection("sessions") .Find(x => x.FolderName == folderName) .OrderByDescending(x => x.CreatedAt) .ToList(); } }