using CartriX.Api.Classes; using CartriX.Api.Entities; using CartriX.Api.Interfaces; using Microsoft.EntityFrameworkCore; namespace CartriX.Api.Services { public class PrinterService : IPrinterService { private readonly AppDbContext _context; public PrinterService(AppDbContext context) { _context = context; } public async Task AddAsync(DTOs.Printer.AddPrinter requestDto) { var manufacturerToAdd = await _context.Manufacturers.FirstOrDefaultAsync(m => m.name == requestDto.manufacturerName); if (manufacturerToAdd is null) { manufacturerToAdd = new Manufacturer { name = requestDto.manufacturerName }; } var modelToAdd = await _context.PrinterModels.Include(m => m.manufacturer).Include(m => m.articles).FirstOrDefaultAsync(m => m.name == requestDto.modelName); if (modelToAdd is null) { List articles = new List(); foreach (string articleName in requestDto.cartridgeArticleNames) { var articleToAdd = await _context.Articles.FirstOrDefaultAsync(a => a.name == articleName); if (articleToAdd is null) { var newArticle = new Article { name = articleName }; articles.Add(newArticle); } else { articles.Add(articleToAdd); } } modelToAdd = new PrinterModel { name = requestDto.modelName, articles = articles, manufacturer = manufacturerToAdd }; } var locationToAdd = await _context.Locations.Include(l => l.printers).FirstOrDefaultAsync(l => l.name == requestDto.locationName); if (locationToAdd is null) { locationToAdd = new Entities.Location { name = requestDto.locationName, printers = new() }; } Entities.Printer newPrinter = new Entities.Printer() { name = requestDto.name, ipAddressOrHostname = requestDto.ipAddressOrHostname, countPrintedAllTime = requestDto.countPrintedAllTime, oidForQueryCountPrintedAllTime = requestDto.oidForQueryCountPrintedAllTime, printTypeId = requestDto.printTypeId, model = modelToAdd, connetctionTypeId = requestDto.connectionTypeId, location = locationToAdd, }; newPrinter.location.printers.Add(newPrinter); await _context.AddAsync(newPrinter); await _context.SaveChangesAsync(); } public async Task> GetPrintTypes() => await _context.PrintTypes.ToListAsync(); public async Task> GetConnectionTypes() => await _context.ConnectionTypes.ToListAsync(); public async Task GetAsync(int id) => await _context.Printers.Include(l => l.location).Include(m => m.model).FirstOrDefaultAsync(p => p.id == id); public async Task> GetModelsAsync() => await _context.PrinterModels.Select(m => m.name).ToListAsync(); } }