using IceCreamShopContracts.BindingModels; using IceCreamShopContracts.SearchModels; using IceCreamShopContracts.StoragesContracts; using IceCreamShopContracts.ViewModels; using IceCreamShopDataModels.Models; using IceCreamShopFileImplement.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IceCreamShopFileImplement.Implements { public class IceCreamStorage : IIceCreamStorage { private readonly DataFileSingleton source; public IceCreamStorage() { source = DataFileSingleton.GetInstance(); } public List GetFullList() { return source.IceCreams .Select(x => x.GetViewModel) .ToList(); } public List GetFilteredList(IceCreamSearchModel model) { if (string.IsNullOrEmpty(model.IceCreamName)) { return new(); } return source.IceCreams .Where(x => x.IceCreamName.Contains(model.IceCreamName)) .Select(x => x.GetViewModel) .ToList(); } public IceCreamViewModel? GetElement(IceCreamSearchModel model) { if (string.IsNullOrEmpty(model.IceCreamName) && !model.Id.HasValue) { return null; } return source.IceCreams .FirstOrDefault(x => (!string.IsNullOrEmpty(model.IceCreamName) && x.IceCreamName == model.IceCreamName) || (model.Id.HasValue && x.Id == model.Id)) ?.GetViewModel; } public IceCreamViewModel? Insert(IceCreamBindingModel model) { model.Id = source.IceCreams.Count > 0 ? source.IceCreams.Max(x => x.Id) + 1 : 1; var newIceCream = IceCream.Create(model); if (newIceCream == null) { return null; } source.IceCreams.Add(newIceCream); source.SaveIceCreams(); return newIceCream.GetViewModel; } public IceCreamViewModel? Update(IceCreamBindingModel model) { var iceCream = source.IceCreams.FirstOrDefault(x => x.Id == model.Id); if (iceCream == null) { return null; } iceCream.Update(model); source.SaveIceCreams(); return iceCream.GetViewModel; } public IceCreamViewModel? Delete(IceCreamBindingModel model) { var iceCream = source.IceCreams.FirstOrDefault(x => x.Id == model.Id); if (iceCream != null) { source.IceCreams.Remove(iceCream); source.SaveIceCreams(); return iceCream.GetViewModel; } return null; } } }