PIbd-23_Starostin_I.K._Ship.../ShipyardBusinessLogic/ShipLogic.cs

120 lines
4.1 KiB
C#
Raw Normal View History

using Microsoft.Extensions.Logging;
using ShipyardContracts.BindingModels;
using ShipyardContracts.BusinessLogicsContracts;
using ShipyardContracts.SearchModels;
using ShipyardContracts.StoragesContracts;
using ShipyardContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShipyardBusinessLogic
{
public class ShipLogic : IShipLogic
{
private readonly ILogger _logger;
private readonly IShipStorage _ShipStorage;
public ShipLogic(ILogger<ShipLogic> logger, IShipStorage ShipStorage)
{
_logger = logger;
_ShipStorage = ShipStorage;
}
public List<ShipViewModel>? ReadList(ShipSearchModel? model)
{
_logger.LogInformation("ReadList. ShipName:{ShipName}. Id:{ Id}", model?.ShipName, model?.Id);
var list = model == null ? _ShipStorage.GetFullList() : _ShipStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public ShipViewModel? ReadElement(ShipSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. ShipName:{ShipName}.Id:{ Id}", model.ShipName, model.Id);
var element = _ShipStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
public bool Create(ShipBindingModel model)
{
CheckModel(model);
if (_ShipStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(ShipBindingModel model)
{
CheckModel(model);
if (_ShipStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(ShipBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_ShipStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
private void CheckModel(ShipBindingModel model, bool withParams =
true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.ShipName))
{
throw new ArgumentNullException("Нет названия корабля",
nameof(model.ShipName));
}
if (model.Price <= 0)
{
throw new ArgumentNullException("Цена кораблей должна быть больше 0", nameof(model.Price));
}
_logger.LogInformation("Ship. Ship:{Ship}. Price:{ Price }. Id: { Id}", model.ShipName, model.Price, model.Id);
var element = _ShipStorage.GetElement(new ShipSearchModel
{
ShipName = model.ShipName
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Компонент с таким названием уже есть");
}
}
}
}