using FlowerShopFileImplement.Models; using FlowerShopFileImplement.Implements; using FlowerShopContracts.StoragesContracts; using FlowerShopContracts.ViewModels; using FlowerShopContracts.SearchModels; using FlowerShopContracts.BindingModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FlowerShopFileImplement.Implements { public class FlowerStorage : IFlowerStorage { private readonly DataFileSingleton source; public FlowerStorage() { source = DataFileSingleton.GetInstance(); } public List GetFullList() { return source.Flowers .Select(x => x.GetViewModel) .ToList(); } public List GetFilteredList(FlowerSearchModel model) { if (string.IsNullOrEmpty(model.FlowerName)) { return new(); } return source.Flowers .Where(x => x.FlowerName.Contains(model.FlowerName)) .Select(x => x.GetViewModel) .ToList(); } public FlowerViewModel? GetElement(FlowerSearchModel model) { if (string.IsNullOrEmpty(model.FlowerName) && !model.Id.HasValue) { return null; } return source.Flowers .FirstOrDefault(x => (!string.IsNullOrEmpty(model.FlowerName) && x.FlowerName == model.FlowerName) || (model.Id.HasValue && x.Id == model.Id)) ?.GetViewModel; } public FlowerViewModel? Insert(FlowerBindingModel model) { model.Id = source.Flowers.Count > 0 ? source.Flowers.Max(x => x.Id) + 1 : 1; var newFlower = Flower.Create(model); if (newFlower == null) { return null; } source.Flowers.Add(newFlower); source.SaveFlowers(); return newFlower.GetViewModel; } public FlowerViewModel? Update(FlowerBindingModel model) { var flower = source.Flowers.FirstOrDefault(x => x.Id == model.Id); if (flower == null) { return null; } flower.Update(model); source.SaveFlowers(); return flower.GetViewModel; } public FlowerViewModel? Delete(FlowerBindingModel model) { var flower = source.Flowers.FirstOrDefault(x => x.Id == model.Id); if (flower != null) { source.Flowers.Remove(flower); source.SaveFlowers(); return flower.GetViewModel; } return null; } } }