diff --git a/SoftwareInstallation/SoftwareInstallationFileImplement/ShopStorage.cs b/SoftwareInstallation/SoftwareInstallationFileImplement/ShopStorage.cs index 96e13bb..526630e 100644 --- a/SoftwareInstallation/SoftwareInstallationFileImplement/ShopStorage.cs +++ b/SoftwareInstallation/SoftwareInstallationFileImplement/ShopStorage.cs @@ -6,6 +6,7 @@ using SoftwareInstallationDataModels.Models; using System; using System.Collections.Generic; using System.Linq; +using System.Numerics; using System.Text; using System.Threading.Tasks; @@ -73,29 +74,48 @@ namespace SoftwareInstallationFileImplement public bool SellPackage(IPackageModel model, int quantity) { - if (source.Shops.Select(x => x.ShopPackages.FirstOrDefault(y => y.Key == model.Id).Value.Item2).Sum() < quantity) + + var package = source.Shops.FirstOrDefault(x => x.Id == model.Id); + if (package == null || !CheckCount(model, quantity)) { return false; } - foreach (var Shop in source.Shops.Where(x => x.ShopPackages.ContainsKey(model.Id))) + foreach (var shop in source.Shops) { - int QuantityInCurrentShop = Shop.ShopPackages[model.Id].Item2; - if (QuantityInCurrentShop <= quantity) + var packages = shop.ShopPackages; + foreach (var elem in packages.Where(x => x.Value.Item1.Id == package.Id)) { - Shop.ShopPackages.Remove(model.Id); - quantity -= QuantityInCurrentShop; + var selling = Math.Min(elem.Value.Item2, quantity); + packages[elem.Value.Item1.Id] = (elem.Value.Item1, elem.Value.Item2 - selling); + quantity -= selling; + + if (quantity <= 0) + { + break; + } } - else + + shop.Update(new ShopBindingModel { - Shop.ShopPackages[model.Id] = (Shop.ShopPackages[model.Id].Item1, QuantityInCurrentShop - quantity); - quantity = 0; - } - if (quantity == 0) - { - return true; - } + Id = model.Id, + Name = shop.Name, + Address = shop.Address, + DateOpening = shop.DateOpening, + ShopPackages = packages, + PackageMaxCount = shop.PackageMaxCount + }); } - return false; + source.SaveShops(); + return true; + + } + public bool CheckCount(IPackageModel model, int quantity) + { + int store = source.Shops + .Select(x => x.ShopPackages + .Select(y => (y.Value.Item1.Id == model.Id ? y.Value.Item2 : 0)) + .Sum()).Sum(); + return store >= quantity; } public ShopViewModel? Update(ShopBindingModel model)