|
| 1 | +using System.Text.Json; |
| 2 | +using BookApp.Models; |
| 3 | + |
| 4 | +namespace BookApp.Services; |
| 5 | + |
| 6 | +public class BookCollection |
| 7 | +{ |
| 8 | + private readonly string _dataFile; |
| 9 | + private List<Book> _books = []; |
| 10 | + |
| 11 | + private static readonly JsonSerializerOptions JsonOptions = new() |
| 12 | + { |
| 13 | + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, |
| 14 | + WriteIndented = true |
| 15 | + }; |
| 16 | + |
| 17 | + public BookCollection(string? dataFile = null) |
| 18 | + { |
| 19 | + _dataFile = dataFile ?? Path.Combine(AppContext.BaseDirectory, "data.json"); |
| 20 | + LoadBooks(); |
| 21 | + } |
| 22 | + |
| 23 | + public IReadOnlyList<Book> Books => _books; |
| 24 | + |
| 25 | + private void LoadBooks() |
| 26 | + { |
| 27 | + try |
| 28 | + { |
| 29 | + var json = File.ReadAllText(_dataFile); |
| 30 | + _books = JsonSerializer.Deserialize<List<Book>>(json, JsonOptions) ?? []; |
| 31 | + } |
| 32 | + catch (FileNotFoundException) |
| 33 | + { |
| 34 | + _books = []; |
| 35 | + } |
| 36 | + catch (JsonException) |
| 37 | + { |
| 38 | + Console.WriteLine("Warning: data.json is corrupted. Starting with empty collection."); |
| 39 | + _books = []; |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + private void SaveBooks() |
| 44 | + { |
| 45 | + var json = JsonSerializer.Serialize(_books, JsonOptions); |
| 46 | + File.WriteAllText(_dataFile, json); |
| 47 | + } |
| 48 | + |
| 49 | + public Book AddBook(string title, string author, int year) |
| 50 | + { |
| 51 | + var book = new Book { Title = title, Author = author, Year = year }; |
| 52 | + _books.Add(book); |
| 53 | + SaveBooks(); |
| 54 | + return book; |
| 55 | + } |
| 56 | + |
| 57 | + public List<Book> ListBooks() => _books; |
| 58 | + |
| 59 | + public Book? FindBookByTitle(string title) |
| 60 | + { |
| 61 | + return _books.Find(b => b.Title.Equals(title, StringComparison.OrdinalIgnoreCase)); |
| 62 | + } |
| 63 | + |
| 64 | + public bool MarkAsRead(string title) |
| 65 | + { |
| 66 | + var book = FindBookByTitle(title); |
| 67 | + if (book is null) return false; |
| 68 | + book.Read = true; |
| 69 | + SaveBooks(); |
| 70 | + return true; |
| 71 | + } |
| 72 | + |
| 73 | + public bool RemoveBook(string title) |
| 74 | + { |
| 75 | + var book = FindBookByTitle(title); |
| 76 | + if (book is null) return false; |
| 77 | + _books.Remove(book); |
| 78 | + SaveBooks(); |
| 79 | + return true; |
| 80 | + } |
| 81 | + |
| 82 | + public List<Book> FindByAuthor(string author) |
| 83 | + { |
| 84 | + return _books |
| 85 | + .Where(b => b.Author.Equals(author, StringComparison.OrdinalIgnoreCase)) |
| 86 | + .ToList(); |
| 87 | + } |
| 88 | +} |
0 commit comments