using SushiBarContracts.BindingModels; using SushiBarContracts.SearchModels; using SushiBarContracts.StoragesContracts; using SushiBarContracts.ViewModels; using SushiBarDataModels.Models; using SushiBarFileImplement.Models; using System.Reflection; namespace SushiBarFileImplement.Implements { public class SushiStorage : ISushiStorage { private readonly DataFileSingleton source; public SushiStorage() { source = DataFileSingleton.GetInstance(); } public List GetFullList() { return source.ListSushi.Select(x => x.GetViewModel).ToList(); } public List GetFilteredList(SushiSearchModel model) { if (string.IsNullOrEmpty(model.SushiName)) { return new(); } return source.ListSushi.Where(x => x.SushiName.Contains(model.SushiName)).Select(x => x.GetViewModel).ToList(); } public SushiViewModel? GetElement(SushiSearchModel model) { if (string.IsNullOrEmpty(model.SushiName) && !model.Id.HasValue) { return null; } return source.ListSushi.FirstOrDefault(x => (!string.IsNullOrEmpty(model.SushiName) && x.SushiName == model.SushiName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; } public SushiViewModel? Insert(SushiBindingModel model) { model.Id = source.ListSushi.Count > 0 ? source.ListSushi.Max(x => x.Id) + 1 : 1; var newSushi = Sushi.Create(model); if (newSushi == null) { return null; } source.ListSushi.Add(newSushi); source.SaveListSushi(); return newSushi.GetViewModel; } public SushiViewModel? Update(SushiBindingModel model) { var sushi = source.ListSushi.FirstOrDefault(x => x.Id == model.Id); if (sushi == null) { return null; } sushi.Update(model); source.SaveListSushi(); return sushi.GetViewModel; } public SushiViewModel? Delete(SushiBindingModel model) { var element = source.ListSushi.FirstOrDefault(x => x.Id == model.Id); if (element != null) { source.ListSushi.Remove(element); source.SaveListSushi(); return element.GetViewModel; } return null; } public bool SellSushi(ISushiModel model, int count) { var temp = source.Shops .Select(x => x.ListSushi .FirstOrDefault(x => x.Key == model.Id).Value.Item2).Sum(); if (temp < count) { return false; } foreach (var shop in source.Shops.Where(x => x.ListSushi.ContainsKey(model.Id))) { if (shop.ListSushi[model.Id].Item2 < count) { shop.ListSushi[model.Id] = (shop.ListSushi[model.Id].Item1, 0); count -= shop.ListSushi[model.Id].Item2; } else { shop.ListSushi[model.Id] = (shop.ListSushi[model.Id].Item1, shop.ListSushi[model.Id].Item2 - count); count -= count; } if (count <= 0) { return true; } } return true; } } }