PIbd-23_Starostin_I.K._Ship.../ShipyardFileImplement/ShipStorage.cs

89 lines
2.7 KiB
C#

using ShipyardContracts.BindingModels;
using ShipyardContracts.SearchModels;
using ShipyardContracts.StoragesContracts;
using ShipyardContracts.ViewModels;
using ShipyardFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 Ship = source.Ships.FirstOrDefault(x => x.Id ==
model.Id);
if (Ship != null)
{
source.Ships.Remove(Ship);
source.SaveShips();
return Ship.GetViewModel;
}
return null;
}
}
}