95 lines
2.7 KiB
C#
Raw Normal View History

2023-04-19 17:22:41 +03:00
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.SearchModel;
using AutomobilePlantContracts.StoragesContracts;
using AutomobilePlantContracts.ViewModel;
using AutomomilePlantFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomomilePlantFileImplement.Implements
{
public class CarStorage : ICarStorage
{
private readonly DataFileSingleton source;
public CarStorage()
{
source = DataFileSingleton.GetInstance();
}
public CarViewModel? Delete(CarBindingModel model)
{
var element = source.Cars.FirstOrDefault(x => x.Id ==
model.Id);
if (element != null)
{
source.Cars.Remove(element);
source.SaveCars();
return element.GetViewModel;
}
return null;
}
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;
}
}
}