PIbd-23_Minhasapov_R.H._Aut.../AutomobilePlant/AutomobilePlantFileImplement/Implements/CarStorage.cs

89 lines
2.6 KiB
C#
Raw Normal View History

2023-03-11 18:47:48 +04:00
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.SearchModels;
using AutomobilePlantContracts.StorageContracts;
using AutomobilePlantContracts.ViewModels;
using AutomobilePlantFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
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;
}
}
}