using AircraftPlantContracts.BindingModels; using AircraftPlantContracts.SearchModels; using AircraftPlantContracts.StoragesContracts; using AircraftPlantContracts.ViewModels; using AircraftPlantDataModels.Models; using AircraftPlantFileImplement; using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; namespace AircraftPlantFileImplement { public class ShopStorage : IShopStorage { private readonly DataFileSingleton _source; public ShopStorage() { _source = DataFileSingleton.GetInstance(); } public List GetFullList() { return _source.Shops .Select(x => x.GetViewModel) .ToList(); } public List GetFilteredList(ShopSearchModel model) { if (string.IsNullOrEmpty(model.ShopName)) { return new(); } return _source.Shops .Where(x => x.ShopName.Contains(model.ShopName)) .Select(x => x.GetViewModel) .ToList(); } public ShopViewModel? GetElement(ShopSearchModel model) { if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue) { return null; } return _source.Shops .FirstOrDefault(x => (!string.IsNullOrEmpty(model.ShopName) && x.ShopName == model.ShopName) || (model.Id.HasValue && x.Id == model.Id)) ?.GetViewModel; } public ShopViewModel? Insert(ShopBindingModel model) { model.Id = _source.Shops.Count > 0 ? _source.Shops.Max(x => x.Id) + 1 : 1; var newShop = Shop.Create(model); if (newShop == null) { return null; } _source.Shops.Add(newShop); _source.SaveShops(); return newShop.GetViewModel; } public ShopViewModel? Update(ShopBindingModel model) { var shop = _source.Shops.FirstOrDefault(x => x.Id == model.Id); if (shop == null) { return null; } shop.Update(model); _source.SaveShops(); return shop.GetViewModel; } public ShopViewModel? Delete(ShopBindingModel model) { var element = _source.Shops.FirstOrDefault(x => x.Id == model.Id); if (element != null) { _source.Shops.Remove(element); _source.SaveShops(); return element.GetViewModel; } return null; } public bool SellPlanes(IPlaneModel model, int count) { var plane = _source.Planes.FirstOrDefault(x => x.Id == model.Id); if (plane == null || !CheckCount(model, count)) { return false; } foreach (var shop in _source.Shops) { var planes = shop.ShopPlanes; foreach (var elem in planes.Where(x => x.Value.Item1.Id == plane.Id)) { var selling = Math.Min(elem.Value.Item2, count); planes[elem.Value.Item1.Id] = (elem.Value.Item1, elem.Value.Item2 - selling); count -= selling; if (count <= 0) { break; } } shop.Update(new ShopBindingModel { Id = model.Id, ShopName = shop.ShopName, Address = shop.Address, DateOpening = shop.DateOpening, ShopPlanes = planes, MaxPlanes = shop.MaxPlanes }); } _source.SaveShops(); return true; } public bool CheckCount(IPlaneModel model, int count) { int store = _source.Shops .Select(x => x.ShopPlanes .Select(y => (y.Value.Item1.Id == model.Id ? y.Value.Item2 : 0)) .Sum()).Sum(); return store >= count; } } }