PIbd-23-Volkov-N.A.-Compute.../ComputersShop/ComputersShopFileImplement/Implements/ComputerStorage.cs

83 lines
2.7 KiB
C#

using ComputersShopContracts.BindingModels;
using ComputersShopContracts.SearchModels;
using ComputersShopContracts.StoragesContracts;
using ComputersShopContracts.ViewModels;
using ComputersShopFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputersShopFileImplement.Implements
{
public class ComputerStorage : IComputerStorage
{
private readonly DataFileSingleton source;
public ComputerStorage()
{
source = DataFileSingleton.GetInstance();
}
public ComputerViewModel? GetElement(ComputerSearchModel model)
{
if (string.IsNullOrEmpty(model.ComputerName) && !model.Id.HasValue)
{
return null;
}
return source.Computers.FirstOrDefault(x => (!string.IsNullOrEmpty(model.ComputerName) && x.ComputerName == model.ComputerName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public List<ComputerViewModel> GetFilteredList(ComputerSearchModel model)
{
if (string.IsNullOrEmpty(model.ComputerName))
{
return new();
}
return source.Computers.Where(x => x.ComputerName.Contains(model.ComputerName)).Select(x => x.GetViewModel).ToList();
}
public List<ComputerViewModel> GetFullList()
{
return source.Computers.Select(x => x.GetViewModel).ToList();
}
public ComputerViewModel? Insert(ComputerBindingModel model)
{
model.Id = source.Computers.Count > 0 ? source.Computers.Max(x => x.Id) + 1 : 1;
var newDoc = Computer.Create(model);
if (newDoc == null)
{
return null;
}
source.Computers.Add(newDoc);
source.SaveComputers();
return newDoc.GetViewModel;
}
public ComputerViewModel? Update(ComputerBindingModel model)
{
var document = source.Computers.FirstOrDefault(x => x.Id == model.Id);
if (document == null)
{
return null;
}
document.Update(model);
source.SaveComputers();
return document.GetViewModel;
}
public ComputerViewModel? Delete(ComputerBindingModel model)
{
var document = source.Computers.FirstOrDefault(x => x.Id == model.Id);
if (document == null)
{
return null;
}
document.Update(model);
source.SaveComputers();
return document.GetViewModel;
}
}
}