ISEbd-21_Agliullov.D.A._Con.../ConfectionaryFileImplement/ShopStorage.cs

113 lines
3.4 KiB
C#
Raw Normal View History

2023-02-15 05:01:38 +04:00
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.SearchModels;
using ConfectioneryContracts.StoragesContract;
using ConfectioneryContracts.ViewModels;
using ConfectioneryDataModels.Models;
2023-02-15 05:01:38 +04:00
namespace ConfectioneryFileImplement
{
public class ShopStorage : IShopStorage
{
private readonly DataFileSingleton _source;
public ShopStorage()
{
_source = DataFileSingleton.GetInstance();
}
public ShopViewModel? Delete(ShopBindingModel model)
{
var element = _source.Shops.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
2023-02-15 05:01:38 +04:00
{
_source.Shops.Remove(element);
_source.SaveShops();
return element.GetViewModel;
2023-02-15 05:01:38 +04:00
}
return null;
}
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (!model.Id.HasValue)
2023-02-15 05:01:38 +04:00
{
return null;
}
return _source.Shops.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)?.GetViewModel;
2023-02-15 05:01:38 +04:00
}
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.Name))
{
return new();
2023-02-15 05:01:38 +04:00
}
return _source.Shops
.Select(x => x.GetViewModel)
.Where(x => x.Name.Contains(model.Name ?? string.Empty))
.ToList();
2023-02-15 05:01:38 +04:00
}
public List<ShopViewModel> GetFullList()
{
return _source.Shops
.Select(shop => shop.GetViewModel)
.ToList();
2023-02-15 05:01:38 +04:00
}
public ShopViewModel? Insert(ShopBindingModel model)
{
model.Id = _source.Shops.Count > 0 ? _source.Shops.Max(x => x.Id) + 1 : 1;
2023-02-15 05:01:38 +04:00
var newShop = Shop.Create(model);
if (newShop == null)
{
return null;
}
_source.Shops.Add(newShop);
_source.SaveShops();
2023-02-15 05:01:38 +04:00
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 bool HasNeedPastries(IPastryModel pastry, int needCount)
{
var resultCount = _source.Shops
.Select(shop => shop.Pastries
.FirstOrDefault(x => x.Key == pastry.Id).Value.Item2)
.Sum();
return resultCount >= needCount;
}
public bool SellPastries(IPastryModel pastry, int needCount)
{
if (!HasNeedPastries(pastry, needCount))
2023-02-15 05:01:38 +04:00
{
return false;
}
foreach (var pair in _source.Shops.Where(shop => shop.Pastries.ContainsKey(pastry.Id)))
{
var tuple = pair.Pastries[pastry.Id];
var diff = Math.Min(tuple.Item2, needCount);
pair.Pastries[pastry.Id] = (tuple.Item1, tuple.Item2 - diff);
needCount -= diff;
if (needCount <= 0)
2023-02-15 05:01:38 +04:00
{
return true;
2023-02-15 05:01:38 +04:00
}
}
return true;
2023-02-15 05:01:38 +04:00
}
}
}