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

86 lines
2.7 KiB
C#
Raw Normal View History

using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.SearchModels;
using ConfectioneryContracts.StoragesContract;
using ConfectioneryContracts.ViewModels;
2023-02-15 04:07:03 +04:00
using ConfectioneryFileImplement.Models;
namespace ConfectioneryFileImplement
{
public class PastryStorage : IPastryStorage
{
private readonly DataFileSingleton _source;
public PastryStorage()
{
_source = DataFileSingleton.GetInstance();
}
public PastryViewModel? Delete(PastryBindingModel model)
{
var element = _source.Pastries.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
_source.Pastries.Remove(element);
2023-02-15 04:07:03 +04:00
_source.SavePastries();
return element.GetViewModel;
}
return null;
}
public PastryViewModel? GetElement(PastrySearchModel model)
{
if (string.IsNullOrEmpty(model.PastryName) && !model.Id.HasValue)
{
return null;
}
return _source.Pastries.FirstOrDefault
(x => (!string.IsNullOrEmpty(model.PastryName) && x.PastryName == model.PastryName) ||
(model.Id.HasValue && x.Id == model.Id)
)?.GetViewModel;
}
public List<PastryViewModel> GetFilteredList(PastrySearchModel model)
{
if (string.IsNullOrEmpty(model.PastryName))
{
return new();
}
return _source.Pastries
.Select(x => x.GetViewModel)
.Where(x => x.PastryName.Contains(model.PastryName))
.ToList();
}
public List<PastryViewModel> GetFullList()
{
return _source.Pastries
.Select(x => x.GetViewModel)
.ToList();
}
public PastryViewModel? Insert(PastryBindingModel model)
{
2023-02-15 04:07:03 +04:00
model.Id = _source.Pastries.Count > 0 ? _source.Pastries.Max(x => x.Id) + 1 : 1;
var newPastry = Pastry.Create(model);
if (newPastry == null)
{
return null;
}
_source.Pastries.Add(newPastry);
_source.SavePastries();
return newPastry.GetViewModel;
}
public PastryViewModel? Update(PastryBindingModel model)
{
var pastry = _source.Pastries.FirstOrDefault(x => x.Id == model.Id);
if (pastry == null)
{
return null;
}
pastry.Update(model);
_source.SavePastries();
return pastry.GetViewModel;
}
}
}