using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; 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.Pastrys.Select(x => x.GetViewModel).ToList(); } public List GetFilteredList(PastrySearchModel model) { if (string.IsNullOrEmpty(model.PastryName)) { return new(); } return source.Pastrys.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.Pastrys.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.Pastrys.Count > 0 ? source.Pastrys.Max(x => x.Id) + 1 : 1; var newPastry = Pastry.Create(model); if (newPastry == null) { return null; } source.Pastrys.Add(newPastry); source.SavePastrys(); return newPastry.GetViewModel; } public PastryViewModel? Update(PastryBindingModel model) { var Pastry = source.Pastrys.FirstOrDefault(x => x.Id == model.Id); if (Pastry == null) { return null; } Pastry.Update(model); source.SavePastrys(); return Pastry.GetViewModel; } public PastryViewModel? Delete(PastryBindingModel model) { var Pastry = source.Pastrys.FirstOrDefault(x => x.Id == model.Id); if (Pastry != null) { source.Pastrys.Remove(Pastry); source.SavePastrys(); return Pastry.GetViewModel; } return null; } } }