using ConfectioneryContracts.BindingModels; using ConfectioneryContracts.SearchModels; using ConfectioneryContracts.StoragesContracts; using ConfectioneryContracts.ViewModels; using ConfectioneryFileImplement.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConfectioneryFileImplement.Implements { public class PastryStorage : IPastryStorage { private readonly DataFileSingleton source; public PastryStorage() { source = DataFileSingleton.GetInstance(); } public PastryViewModel? GetElement(PastrySearchModel model) { if (string.IsNullOrEmpty(model.PastryName) && !model.Id.HasValue) { return null; } return source.Pastries.FirstOrDefault(x => (!string.IsNullOrEmpty(model.PastryName) && x.PastryName == model.PastryName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; } public List GetFilteredList(PastrySearchModel model) { if (string.IsNullOrEmpty(model.PastryName)) { return new(); } return source.Pastries.Where(x => x.PastryName.Contains(model.PastryName)).Select(x => x.GetViewModel).ToList(); } public List GetFullList() { return source.Pastries.Select(x => x.GetViewModel).ToList(); } public PastryViewModel? Insert(PastryBindingModel model) { model.Id = source.Pastries.Count > 0 ? source.Pastries.Max(x => x.Id) + 1 : 1; var newDoc = Pastry.Create(model); if (newDoc == null) { return null; } source.Pastries.Add(newDoc); source.SavePastries(); return newDoc.GetViewModel; } public PastryViewModel? Update(PastryBindingModel model) { var document = source.Pastries.FirstOrDefault(x => x.Id == model.Id); if (document == null) { return null; } document.Update(model); source.SavePastries(); return document.GetViewModel; } public PastryViewModel? Delete(PastryBindingModel model) { var document = source.Pastries.FirstOrDefault(x => x.Id == model.Id); if (document == null) { return null; } document.Update(model); source.SavePastries(); return document.GetViewModel; } } }