PIbd-21_RazubaevSM_Plumbing.../PlumbingRepair/PlumbingRepairFileImplement/Implements/WorkStorage.cs
2024-03-23 19:49:48 +04:00

85 lines
2.6 KiB
C#

using PlumbingRepairContracts.BindingModels;
using PlumbingRepairContracts.SearchModels;
using PlumbingRepairContracts.StoragesContracts;
using PlumbingRepairContracts.ViewModels;
using PlumbingRepairFileImplement.Models;
namespace PlumbingRepairFileImplement.Implements
{
public class WorkStorage : IWorkStorage
{
private readonly DataFileSingleton source;
public WorkStorage()
{
source = DataFileSingleton.GetInstance();
}
public WorkViewModel? Delete(WorkBindingModel model)
{
var element = source.Works.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
source.Works.Remove(element);
source.SaveWorks();
return element.GetViewModel;
}
return null;
}
public WorkViewModel? GetElement(WorkSearchModel model)
{
if (string.IsNullOrEmpty(model.WorkName) && !model.Id.HasValue)
{
return null;
}
return source.Works
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.WorkName) && x.WorkName == model.WorkName) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public List<WorkViewModel> GetFilteredList(WorkSearchModel model)
{
if (string.IsNullOrEmpty(model.WorkName))
{
return new();
}
return source.Works
.Where(x => x.WorkName.Contains(model.WorkName))
.Select(x => x.GetViewModel)
.ToList();
}
public List<WorkViewModel> GetFullList()
{
return source.Works
.Select(x => x.GetViewModel)
.ToList();
}
public WorkViewModel? Insert(WorkBindingModel model)
{
model.Id = source.Works.Count > 0 ? source.Works.Max(x => x.Id) + 1 : 1;
var newWork = Work.Create(model);
if (newWork == null)
{
return null;
}
source.Works.Add(newWork);
source.SaveWorks();
return newWork.GetViewModel;
}
public WorkViewModel? Update(WorkBindingModel model)
{
var work = source.Works.FirstOrDefault(x => x.Id == model.Id);
if (work == null)
{
return null;
}
work.Update(model);
source.SaveWorks();
return work.GetViewModel;
}
}
}