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

108 lines
3.2 KiB
C#

using ShipyardContracts.ViewModels;
using ShipyardContracts.SearchModels;
using ShipyardContracts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ShipyardContracts.StoragesContracts;
using ShipyardListImplement.Models;
namespace ShipyardListImplement
{
public class ShipStorage : IShipStorage
{
private readonly DataListSingleton _source;
public ShipStorage()
{
_source = DataListSingleton.GetInstance();
}
public List<ShipViewModel> GetFullList()
{
var result = new List<ShipViewModel>();
foreach (var Ship in _source.Ships)
{
result.Add(Ship.GetViewModel);
}
return result;
}
public List<ShipViewModel> GetFilteredList(ShipSearchModel model)
{
var result = new List<ShipViewModel>();
if (string.IsNullOrEmpty(model.ShipName))
{
return result;
}
foreach (var Ship in _source.Ships)
{
if (Ship.ShipName.Contains(model.ShipName))
{
result.Add(Ship.GetViewModel);
}
}
return result;
}
public ShipViewModel? GetElement(ShipSearchModel model)
{
if (string.IsNullOrEmpty(model.ShipName) && !model.Id.HasValue)
{
return null;
}
foreach (var Ship in _source.Ships)
{
if ((!string.IsNullOrEmpty(model.ShipName) &&
Ship.ShipName == model.ShipName) ||
(model.Id.HasValue && Ship.Id == model.Id))
{
return Ship.GetViewModel;
}
}
return null;
}
public ShipViewModel? Insert(ShipBindingModel model)
{
model.Id = 1;
foreach (var Ship in _source.Ships)
{
if (model.Id <= Ship.Id)
{
model.Id = Ship.Id + 1;
}
}
var newShip = Ship.Create(model);
if (newShip == null)
{
return null;
}
_source.Ships.Add(newShip);
return newShip.GetViewModel;
}
public ShipViewModel? Update(ShipBindingModel model)
{
foreach (var Ship in _source.Ships)
{
if (Ship.Id == model.Id)
{
Ship.Update(model);
return Ship.GetViewModel;
}
}
return null;
}
public ShipViewModel? Delete(ShipBindingModel model)
{
for (int i = 0; i < _source.Ships.Count; ++i)
{
if (_source.Ships[i].Id == model.Id)
{
var element = _source.Ships[i];
_source.Ships.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
}
}