75 lines
2.5 KiB
C#
Raw Permalink Normal View History

2024-03-15 14:49:38 +04:00
using DinerContracts.BindingModels;
using DinerContracts.SearchModels;
using DinerContracts.StoragesContracts;
using DinerContracts.ViewModels;
using DinerFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DinerFileImplement.Implements
{
public class SnackStorage : ISnackStorage
{
private readonly DataFileSingleton _source;
public SnackStorage()
{
_source = DataFileSingleton.GetInstance();
}
public SnackViewModel? Delete(SnackBindingModel model)
{
var element = _source.Snacks.FirstOrDefault(x => x.ID == model.ID);
if (element != null) {
_source.Snacks.Remove(element);
_source.SaveSnacks();
return element.GetViewModel;
}
return null;
}
public SnackViewModel? GetElement(SnackSearchModel model)
{
if (string.IsNullOrEmpty(model.ProductName) && !model.ID.HasValue) { return null; }
return _source.Snacks
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.ProductName) &&
x.ProductName == model.ProductName) || model.ID.HasValue &&
x.ID == model.ID)?.GetViewModel;
}
public List<SnackViewModel> GetFilteredList(SnackSearchModel model)
{
if (string.IsNullOrEmpty(model.ProductName)) { return new(); }
return _source.Snacks.Where(x => x.ProductName.Contains(model.ProductName))
.Select(x => x.GetViewModel).ToList();
}
public List<SnackViewModel> GetFullList()
{
return _source.Snacks.Select(x => x.GetViewModel).ToList();
}
public SnackViewModel? Insert(SnackBindingModel model)
{
model.ID = _source.Snacks.Count > 0 ? _source.Snacks.Max(x => x.ID) + 1 : 1;
var newProduct = Snack.Create(model);
if (newProduct == null) { return null; }
_source.Snacks.Add(newProduct);
_source.SaveSnacks();
return newProduct.GetViewModel;
}
public SnackViewModel? Update(SnackBindingModel model)
{
var product = _source.Snacks.FirstOrDefault(x => x.ID == model.ID);
if (product == null) { return null; }
product.Update(model);
_source.SaveSnacks();
return product.GetViewModel;
}
}
}