113 lines
3.4 KiB
C#
113 lines
3.4 KiB
C#
using ConfectioneryContracts.BindingModels;
|
|
using ConfectioneryContracts.SearchModels;
|
|
using ConfectioneryContracts.StoragesContract;
|
|
using ConfectioneryContracts.ViewModels;
|
|
using ConfectioneryDataModels.Models;
|
|
|
|
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)
|
|
{
|
|
_source.Shops.Remove(element);
|
|
_source.SaveShops();
|
|
return element.GetViewModel;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
public ShopViewModel? GetElement(ShopSearchModel model)
|
|
{
|
|
if (!model.Id.HasValue)
|
|
{
|
|
return null;
|
|
}
|
|
return _source.Shops.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)?.GetViewModel;
|
|
}
|
|
|
|
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
|
|
{
|
|
if (string.IsNullOrEmpty(model.Name))
|
|
{
|
|
return new();
|
|
}
|
|
return _source.Shops
|
|
.Select(x => x.GetViewModel)
|
|
.Where(x => x.Name.Contains(model.Name ?? string.Empty))
|
|
.ToList();
|
|
}
|
|
|
|
public List<ShopViewModel> GetFullList()
|
|
{
|
|
return _source.Shops
|
|
.Select(shop => shop.GetViewModel)
|
|
.ToList();
|
|
}
|
|
|
|
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 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))
|
|
{
|
|
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)
|
|
{
|
|
return true;
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
}
|
|
}
|