using ConfectioneryContracts.BindingModels; using ConfectioneryContracts.SearchModels; using ConfectioneryContracts.StoragesContract; using ConfectioneryContracts.ViewModels; using ConfectioneryFileImplement.Models; namespace ConfectioneryFileImplement { public class PastryStorage : IPastryStorage { private readonly DataFileSingleton _source; public PastryStorage() { _source = DataFileSingleton.GetInstance(); } public PastryViewModel? Delete(PastryBindingModel model) { var element = _source.Pastries.FirstOrDefault(x => x.Id == model.Id); if (element != null) { _source.Pastries.Remove(element); _source.SavePastries(); return element.GetViewModel; } return null; } 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 .Select(x => x.GetViewModel) .Where(x => x.PastryName.Contains(model.PastryName)) .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 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; } } }