80 lines
2.7 KiB
C#
Raw Normal View History

2023-05-04 03:45:21 +04:00
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.SearchModels;
using ConfectioneryContracts.StoragesContracts;
using ConfectioneryContracts.ViewModels;
using ConfectioneryFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConfectioneryFileImplement.Implements
{
public class SweetsStorage : ISweetsStorage
{
private readonly DataFileSingleton source;
public SweetsStorage()
{
source = DataFileSingleton.GetInstance();
}
public List<SweetsViewModel> GetFullList()
{
return source.ListSweets.Select(x => x.GetViewModel).ToList();
}
public List<SweetsViewModel> GetFilteredList(SweetsSearchModel model)
{
if (string.IsNullOrEmpty(model.SweetsName))
{
return new();
}
return source.ListSweets.Where(x =>
x.SweetsName.Contains(model.SweetsName)).Select(x => x.GetViewModel).ToList();
}
public SweetsViewModel? GetElement(SweetsSearchModel model)
{
if (string.IsNullOrEmpty(model.SweetsName) && !model.Id.HasValue)
{
return null;
}
return source.ListSweets.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.SweetsName) && x.SweetsName ==
model.SweetsName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public SweetsViewModel? Insert(SweetsBindingModel model)
{
model.Id = source.ListSweets.Count > 0 ? source.ListSweets.Max(x => x.Id) + 1 : 1;
var newSweets = Sweets.Create(model);
if (newSweets == null)
{
return null;
}
source.ListSweets.Add(newSweets);
source.SaveListSweets();
return newSweets.GetViewModel;
}
public SweetsViewModel? Update(SweetsBindingModel model)
{
var sweets = source.ListSweets.FirstOrDefault(x => x.Id == model.Id);
if (sweets == null)
{
return null;
}
sweets.Update(model);
source.SaveListSweets();
return sweets.GetViewModel;
}
public SweetsViewModel? Delete(SweetsBindingModel model)
{
var element = source.ListSweets.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
source.ListSweets.Remove(element);
source.SaveListSweets();
return element.GetViewModel;
}
return null;
}
}
}