PIbd-21_Zaharchenko_M.I._Pi.../Pizzeria/PizzeriaFileImplement/Implements/PizzaStorage.cs

75 lines
2.5 KiB
C#
Raw Normal View History

2023-02-22 08:21:55 +04:00
using PizzeriaContracts.BindingModels;
using PizzeriaContracts.SearchModels;
using PizzeriaContracts.StoragesContracts;
using PizzeriaContracts.ViewModels;
using PizzeriaFileImplement.Models;
namespace PizzeriaFileImplement.Implements
{
public class PizzaStorage : IPizzaStorage
{
2023-03-08 14:33:19 +04:00
private readonly DataFileSingleton source;
2023-02-22 08:21:55 +04:00
public PizzaStorage()
{
2023-03-08 14:33:19 +04:00
source = DataFileSingleton.GetInstance();
2023-02-22 08:21:55 +04:00
}
public List<PizzaViewModel> GetFullList()
{
2023-03-08 14:33:19 +04:00
return source.Pizzas.Select(x => x.GetViewModel).ToList();
2023-02-22 08:21:55 +04:00
}
public List<PizzaViewModel> GetFilteredList(PizzaSearchModel model)
{
if (string.IsNullOrEmpty(model.PizzaName))
{
2023-03-08 14:33:19 +04:00
return new();
2023-02-22 08:21:55 +04:00
}
2023-03-08 14:33:19 +04:00
return source.Pizzas.Where(x => x.PizzaName.Contains(model.PizzaName)).Select(x => x.GetViewModel).ToList();
2023-02-22 08:21:55 +04:00
}
public PizzaViewModel? GetElement(PizzaSearchModel model)
{
if (string.IsNullOrEmpty(model.PizzaName) && !model.Id.HasValue)
{
return null;
}
2023-03-08 14:33:19 +04:00
return source.Pizzas.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.PizzaName) && x.PizzaName == model.PizzaName) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
2023-02-22 08:21:55 +04:00
}
public PizzaViewModel? Insert(PizzaBindingModel model)
{
2023-03-08 14:33:19 +04:00
model.Id = source.Pizzas.Count > 0 ? source.Pizzas.Max(x => x.Id) + 1 : 1;
var newPizza = Pizza.Create(model);
if (newPizza == null)
2023-02-22 08:21:55 +04:00
{
return null;
}
2023-03-08 14:33:19 +04:00
source.Pizzas.Add(newPizza);
source.SavePizzas();
return newPizza.GetViewModel;
2023-02-22 08:21:55 +04:00
}
public PizzaViewModel? Update(PizzaBindingModel model)
{
2023-03-08 14:33:19 +04:00
var Pizza = source.Pizzas.FirstOrDefault(x => x.Id == model.Id);
if (Pizza == null)
2023-02-22 08:21:55 +04:00
{
2023-03-08 14:33:19 +04:00
return null;
2023-02-22 08:21:55 +04:00
}
2023-03-08 14:33:19 +04:00
Pizza.Update(model);
source.SavePizzas();
return Pizza.GetViewModel;
2023-02-22 08:21:55 +04:00
}
public PizzaViewModel? Delete(PizzaBindingModel model)
{
2023-03-08 14:33:19 +04:00
var Pizza = source.Pizzas.FirstOrDefault(x => x.Id == model.Id);
if (Pizza != null)
2023-02-22 08:21:55 +04:00
{
2023-03-08 14:33:19 +04:00
source.Pizzas.Remove(Pizza);
source.SavePizzas();
return Pizza.GetViewModel;
2023-02-22 08:21:55 +04:00
}
return null;
}
}
}