using ConfectioneryContracts.BindingModels; using ConfectioneryContracts.SearchModels; using ConfectioneryContracts.StoragesContracts; using ConfectioneryContracts.ViewModels; using ConfectioneryFileImplement.Models; namespace ConfectioneryFileImplement.Implements { public class PastryStorage : IPastryStorage { private readonly DataFileSingleton source; public PastryStorage() { source = DataFileSingleton.GetInstance(); } public List GetFullList() { return source.Pastries .Select(x => x.GetViewModel) .ToList(); } 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 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 PastryViewModel? Insert(PastryBindingModel model) { model.Id = source.Pastries.Count > 0 ? source.Pastries.Max(x => x.Id) + 1 : 1; var newPastry = Pastry.Create(model); if (newPastry == null) { return null; } source.Pastries.Add(newPastry); source.SavePastries(); return newPastry.GetViewModel; } public PastryViewModel? Update(PastryBindingModel model) { var Pastry = source.Pastries.FirstOrDefault(x => x.Id == model.Id); if (Pastry == null) { return null; } Pastry.Update(model); source.SavePastries(); return Pastry.GetViewModel; } public PastryViewModel? Delete(PastryBindingModel model) { var Pastry = source.Pastries.FirstOrDefault(x => x.Id == model.Id); if (Pastry != null) { source.Pastries.Remove(Pastry); source.SavePastries(); return Pastry.GetViewModel; } return null; } } }