using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Entity; using Shared; using static System.Runtime.InteropServices.JavaScript.JSType; namespace Contextlib { public class DbSourceManager : ISourceService { private WTFContext _context; private GenericRepository _repo; public DbSourceManager(WTFContext context) { _context = context ?? throw new ArgumentNullException(nameof(context), "Database context cannot be null."); _repo = new GenericRepository(_context); } public async Task AddSource(Source source) { if (source == null) { throw new ArgumentNullException(nameof(source), "character cannot be null."); } _repo.Insert(source); await _context.SaveChangesAsync(); } public async Task> GetAll() { List srcLst = _repo.GetItems(0, _repo.Count(), []).ToList(); return new PaginationResult(srcLst.Count, 0, srcLst.Count, srcLst); } public async Task GetLastSourceId() { throw new NotImplementedException(); } public async Task> GetSomesSource(int page, int count) { var srcLst = _repo.GetItems(page, count, []).ToList(); return new PaginationResult(srcLst.Count, 0, srcLst.Count, srcLst); } public async Task> GetSourceByDate(int date) { var srcLst = _repo.GetItems(item => item.Year == date, 0, _repo.Count(), []).ToList(); return new PaginationResult(srcLst.Count, 0, srcLst.Count, srcLst); } public async Task GetSourceById(int id) { Source? source = _repo.GetById(id, item => item.Id == id, []); if (source == null) { throw new KeyNotFoundException($"Error : No source found with the ID: {id}."); } return source; } public async Task GetSourceByTitle(string title) { var source = _repo.GetItems(item => item.Title == title, 0, 1, []).FirstOrDefault(); return source; } public async Task GetSourceByType(int type) { var source = _repo.GetItems(item => item.TypeSrc == (TypeSrcEnum)type, 0, 1, []).FirstOrDefault(); return source; } public async Task RemoveSource(int id) { _repo.Delete(id); await _context.SaveChangesAsync(); } public async Task UpdateSource(int id, Source source) { Source? src = _repo.GetById(id); if (src != null) { bool change = false; if (src.Title != source.Title) { src.Title = source.Title; change = true; } if (src.Year != source.Year) { src.Year = source.Year; change = true; } if (src.TypeSrc != source.TypeSrc) { src.TypeSrc = source.TypeSrc; change = true; } _repo.Update(src); if (change) _context.SaveChanges(); } } } }