73 lines
2.4 KiB
C#

using ShipyardContracts.BindingModels;
using ShipyardContracts.StoragesContracts;
using ShipyardContracts.ViewModels;
using ShipyardContracts.SearchModels;
using ShipyardFileImplement.Models;
namespace ShipyardFileImplement.Implements
{
public class ShipStorage : IShipStorage
{
private readonly DataFileSingleton source;
public ShipStorage()
{
source = DataFileSingleton.GetInstance();
}
public List<ShipViewModel> GetFullList()
{
return source.Ships.Select(x => x.GetViewModel).ToList();
}
public List<ShipViewModel> GetFilteredList(ShipSearchModel model)
{
if (string.IsNullOrEmpty(model.ShipName))
{
return new();
}
return source.Ships.Where(x => x.ShipName.Contains(model.ShipName)).Select(x => x.GetViewModel).ToList();
}
public ShipViewModel? GetElement(ShipSearchModel model)
{
if (string.IsNullOrEmpty(model.ShipName) && !model.Id.HasValue)
{
return null;
}
return source.Ships.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.ShipName) && x.ShipName ==
model.ShipName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public ShipViewModel? Insert(ShipBindingModel model)
{
model.Id = source.Ships.Count > 0 ? source.Ships.Max(x => x.Id) + 1 : 1;
var newShip = Ship.Create(model);
if (newShip == null)
{
return null;
}
source.Ships.Add(newShip);
source.SaveShips();
return newShip.GetViewModel;
}
public ShipViewModel? Update(ShipBindingModel model)
{
var ship = source.Ships.FirstOrDefault(x => x.Id == model.Id);
if (ship == null)
{
return null;
}
ship.Update(model);
source.SaveShips();
return ship.GetViewModel;
}
public ShipViewModel? Delete(ShipBindingModel model)
{
var element = source.Ships.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
source.Ships.Remove(element);
source.SaveShips();
return element.GetViewModel;
}
return null;
}
}
}