PIbd-23-Salin-O.A.-IceCream.../IceCreamShop/IceCreamShopFileImplement/Implements/IceCreamStorage.cs
gg12 darfren d510da711a Ready
2024-03-04 15:28:55 +04:00

98 lines
2.9 KiB
C#

using IceCreamShopContracts.BindingModels;
using IceCreamShopContracts.SearchModels;
using IceCreamShopContracts.StoragesContracts;
using IceCreamShopContracts.ViewModels;
using IceCreamShopDataModels.Models;
using IceCreamShopFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IceCreamShopFileImplement.Implements
{
public class IceCreamStorage : IIceCreamStorage
{
private readonly DataFileSingleton source;
public IceCreamStorage()
{
source = DataFileSingleton.GetInstance();
}
public List<IceCreamViewModel> GetFullList()
{
return source.IceCreams
.Select(x => x.GetViewModel)
.ToList();
}
public List<IceCreamViewModel> GetFilteredList(IceCreamSearchModel
model)
{
if (string.IsNullOrEmpty(model.IceCreamName))
{
return new();
}
return source.IceCreams
.Where(x => x.IceCreamName.Contains(model.IceCreamName))
.Select(x => x.GetViewModel)
.ToList();
}
public IceCreamViewModel? GetElement(IceCreamSearchModel model)
{
if (string.IsNullOrEmpty(model.IceCreamName) && !model.Id.HasValue)
{
return null;
}
return source.IceCreams
.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.IceCreamName) && x.IceCreamName ==
model.IceCreamName) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public IceCreamViewModel? Insert(IceCreamBindingModel model)
{
model.Id = source.IceCreams.Count > 0 ? source.IceCreams.Max(x =>
x.Id) + 1 : 1;
var newIceCream = IceCream.Create(model);
if (newIceCream == null)
{
return null;
}
source.IceCreams.Add(newIceCream);
source.SaveIceCreams();
return newIceCream.GetViewModel;
}
public IceCreamViewModel? Update(IceCreamBindingModel model)
{
var iceCream = source.IceCreams.FirstOrDefault(x => x.Id ==
model.Id);
if (iceCream == null)
{
return null;
}
iceCream.Update(model);
source.SaveIceCreams();
return iceCream.GetViewModel;
}
public IceCreamViewModel? Delete(IceCreamBindingModel model)
{
var iceCream = source.IceCreams.FirstOrDefault(x => x.Id ==
model.Id);
if (iceCream != null)
{
source.IceCreams.Remove(iceCream);
source.SaveIceCreams();
return iceCream.GetViewModel;
}
return null;
}
}
}