using Entity; using Microsoft.EntityFrameworkCore; using Shared; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace Contextlib { public class DbImagesManager : IImagesService { private WTFContext _context; public DbImagesManager(WTFContext context) { _context = context ?? throw new ArgumentNullException(nameof(context), "Database context cannot be null."); } public async Task AddImage(Images image) { await _context.AddAsync(image); await _context.SaveChangesAsync(); } public async Task> GetAllImage() { var images = await _context.images.ToListAsync(); return new PaginationResult(images.Count, 0, images.Count, images); } public async Task GetImageById(int id) { var image = await _context.images.Where(x => x.Id == id).FirstOrDefaultAsync(); if (image == null) { throw new KeyNotFoundException($"No image found with the given ID: {id}."); } return image; } public async Task GetLastImageId() { var last = await _context.images.OrderByDescending(x => x.Id).FirstOrDefaultAsync(); if (last == null) { return 0; } return last.Id; } public async Task> GetSomeImage(int index, int pageSize) { var images = await _context.images.ToListAsync(); if (!images.Any()) { throw new KeyNotFoundException($"No images found"); } if ((index * pageSize + pageSize) > images.Count) { if (pageSize > images.Count) { return new PaginationResult(images.Count(), index, pageSize, images); } else { return new PaginationResult(pageSize, index, pageSize, images.Skip(index * pageSize - (((index * pageSize) + pageSize) - images.Count)).Take(pageSize).ToList()); } } return new PaginationResult(images.Count, index, pageSize, images.Skip(index * pageSize).Take(pageSize).ToList()); } public async Task RemoveImage(int id) { var image = await _context.images.Where(x => x.Id == id).FirstOrDefaultAsync(); if (image == null) { throw new KeyNotFoundException($"No image found with the given ID: {id}."); } _context.images.Remove(image); await _context.SaveChangesAsync(); } public async Task UpdateImage(int id, Images image) { var modif = false; var img = await _context.images.Where(x => x.Id == id).FirstOrDefaultAsync(); if (image == null) { throw new ArgumentNullException(nameof(image), "The updated image data cannot be null."); } if (img == null) { throw new KeyNotFoundException($"No image found with the given ID: {id}."); } if (image.ImgPath != null) { img.ImgPath = image.ImgPath; modif = true; } if (modif) { await _context.SaveChangesAsync(); } } } }