PIbd-21_Balberova_D.N._Sush.../SushiBar/SushiBarFileImplement/Implements/SushiStorage.cs

75 lines
2.5 KiB
C#

using SushiBarContracts.BindingModels;
using SushiBarContracts.SearchModels;
using SushiBarContracts.StoragesContracts;
using SushiBarContracts.ViewModels;
using SushiBarFileImplement.Models;
namespace SushiBarFileImplement.Implements
{
public class SushiStorage : ISushiStorage
{
private readonly DataFileSingleton source;
public SushiStorage()
{
source = DataFileSingleton.GetInstance();
}
public List<SushiViewModel> GetFullList()
{
return source.ListSushi.Select(x => x.GetViewModel).ToList();
}
public List<SushiViewModel> GetFilteredList(SushiSearchModel model)
{
if (string.IsNullOrEmpty(model.SushiName))
{
return new();
}
return source.ListSushi.Where(x =>
x.SushiName.Contains(model.SushiName)).Select(x => x.GetViewModel).ToList();
}
public SushiViewModel? GetElement(SushiSearchModel model)
{
if (string.IsNullOrEmpty(model.SushiName) && !model.Id.HasValue)
{
return null;
}
return source.ListSushi.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.SushiName) && x.SushiName ==
model.SushiName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public SushiViewModel? Insert(SushiBindingModel model)
{
model.Id = source.ListSushi.Count > 0 ? source.ListSushi.Max(x => x.Id) + 1 : 1;
var newSushi = Sushi.Create(model);
if (newSushi == null)
{
return null;
}
source.ListSushi.Add(newSushi);
source.SaveListSushi();
return newSushi.GetViewModel;
}
public SushiViewModel? Update(SushiBindingModel model)
{
var sushi = source.ListSushi.FirstOrDefault(x => x.Id == model.Id);
if (sushi == null)
{
return null;
}
sushi.Update(model);
source.SaveListSushi();
return sushi.GetViewModel;
}
public SushiViewModel? Delete(SushiBindingModel model)
{
var element = source.ListSushi.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
source.ListSushi.Remove(element);
source.SaveListSushi();
return element.GetViewModel;
}
return null;
}
}
}