PIbd-21_Kouvshinoff_T._A._A.../AutomobilePlant/AutomobilePlantFileImplement/Implements/CarStorage.cs
2024-02-23 23:56:48 +04:00

87 lines
2.5 KiB
C#

using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.SearchModels;
using AutomobilePlantContracts.StoragesContracts;
using AutomobilePlantContracts.ViewModels;
using AutomobilePlantFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomobilePlantFileImplement.Implements
{
public class CarStorage : ICarStorage
{
private readonly DataFileSingleton source;
public CarStorage()
{
source = DataFileSingleton.GetInstance();
}
public CarViewModel? GetElement(CarSearchModel model)
{
if (string.IsNullOrEmpty(model.CarName) && !model.Id.HasValue)
{
return null;
}
return source.Cars
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.CarName) && x.CarName == model.CarName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public List<CarViewModel> GetFilteredList(CarSearchModel model)
{
if (string.IsNullOrEmpty(model.CarName))
{
return new();
}
return source.Cars
.Where(x => x.CarName.Contains(model.CarName))
.Select(x => x.GetViewModel)
.ToList();
}
public List<CarViewModel> GetFullList()
{
return source.Cars.Select(x => x.GetViewModel).ToList();
}
public CarViewModel? Insert(CarBindingModel model)
{
model.Id = source.Cars.Count > 0 ? source.Cars.Max(x => x.Id) + 1 : 1;
var newCar = Car.Create(model);
if (newCar == null)
{
return null;
}
source.Cars.Add(newCar);
source.SaveCars();
return newCar.GetViewModel;
}
public CarViewModel? Update(CarBindingModel model)
{
var car = source.Cars.FirstOrDefault(x => x.Id == model.Id);
if (car == null)
{
return null;
}
car.Update(model);
source.SaveCars();
return car.GetViewModel;
}
public CarViewModel? Delete(CarBindingModel model)
{
var car = source.Cars.FirstOrDefault(x => x.Id == model.Id);
if (car == null)
{
return null;
}
source.Cars.Remove(car);
source.SaveCars();
return car.GetViewModel;
}
}
}