PIbd-23-Radaev-A.V.-GiftShop/GiftShop/GiftShopFileImplement/Implements/GiftStorage.cs

93 lines
2.5 KiB
C#
Raw Normal View History

2024-04-07 10:14:11 +04:00
using GiftShopContracts.BindingModels;
using GiftShopContracts.SearchModels;
using GiftShopContracts.StoragesContracts;
using GiftShopContracts.ViewModels;
using GiftShopFileImplement.Models;
namespace GiftShopFileImplement.Implements
{
public class GiftStorage : IGiftStorage
{
private readonly DataFileSingleton source;
public GiftStorage()
{
source = DataFileSingleton.GetInstance();
}
public GiftViewModel? Delete(GiftBindingModel model)
{
var element = source.Gifts.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
source.Gifts.Remove(element);
source.SaveGifts();
return element.GetViewModel;
}
return null;
}
public GiftViewModel? GetElement(GiftSearchModel model)
{
if (string.IsNullOrEmpty(model.GiftName) && !model.Id.HasValue)
{
return null;
}
return source.Gifts.FirstOrDefault(x => (!string.IsNullOrEmpty(model.GiftName) && x.GiftName == model.GiftName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public List<GiftViewModel> GetFilteredList(GiftSearchModel model)
{
if (string.IsNullOrEmpty(model.GiftName))
{
return new();
}
return source.Gifts
.Where(x => x.GiftName
.Contains(model.GiftName))
.Select(x => x.GetViewModel).ToList();
}
public List<GiftViewModel> GetFullList()
{
return source.Gifts.Select(x => x.GetViewModel).ToList();
}
public GiftViewModel? Insert(GiftBindingModel model)
{
model.Id = source.Gifts.Count > 0 ? source.Gifts.Max(x => x.Id) + 1 : 1;
var newGift = Gift.Create(model);
if (newGift == null)
{
return null;
}
source.Gifts.Add(newGift);
source.SaveGifts();
return newGift.GetViewModel;
}
public GiftViewModel? Update(GiftBindingModel model)
{
var gift = source.Gifts.FirstOrDefault(x => x.Id == model.Id);
if (gift == null)
{
return null;
}
gift.Update(model);
source.SaveGifts();
return gift.GetViewModel;
}
}
}