PIbd22_Kuznetsov_A.V._Sewin.../SewingDresses/SewingDressesFileImplement/Implements/ClientStorage.cs

62 lines
2.3 KiB
C#
Raw Normal View History

2024-05-26 13:34:14 +04:00
using SewingDressesContracts.StoragesContracts;
using SewingDressesContracts.BindingModels;
using SewingDressesContracts.SearchModels;
using SewingDressesFileImplement.Models;
using SewingDressesContracts.ViewModels;
namespace SewingDressesFileImplement.Implements
{
public class ClientStorage : IClientStorage
{
private readonly DataFileSingleton _source;
public ClientStorage()
{
_source = DataFileSingleton.GetInstance();
}
public ClientViewModel? Insert(ClientBindingModel model)
{
model.Id = _source.Clients.Count > 0 ? _source.Clients.Max(client => client.Id) + 1 : 1;
var newClient = Client.Create(model);
if (newClient == null) { return null; }
_source.Clients.Add(newClient);
_source.SaveClients();
return newClient.GetViewModel;
}
public ClientViewModel? Update(ClientBindingModel model)
{
var client = _source.Clients.FirstOrDefault(x => x.Id == model.Id);
if (client == null) { return null; };
client.Update(model);
_source.SaveClients();
return client.GetViewModel;
}
public ClientViewModel? Delete(ClientBindingModel model)
{
var client = _source.Clients.FirstOrDefault(client => client.Id == model.Id);
if (client == null) { return null; }
_source.Clients.Remove(client);
_source.SaveClients();
return client.GetViewModel;
}
public ClientViewModel? GetElement(ClientSearchModel model)
{
if (string.IsNullOrEmpty(model.Email) && !model.Id.HasValue) { return null; }
return _source.Clients.FirstOrDefault(x => (!(string.IsNullOrEmpty(model.Email)) && model.Email == x.Email) || (model.Id.HasValue && model.Id == x.Id))?.GetViewModel;
}
public List<ClientViewModel> GetFilteredList(ClientSearchModel model)
{
if (string.IsNullOrEmpty(model.Email)) { return new(); }
return _source.Clients.Where(x => x.Email.Equals(model.Email)).Select(x => x.GetViewModel).ToList();
}
public List<ClientViewModel> GetFullList()
{
return _source.Clients.Select(x => x.GetViewModel).ToList();
}
}
}