108 lines
3.9 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;
namespace ShipyardBusinessLogic.BusinessLogics
{
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. ShipName:{ShipName}. 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("Корабль с таким названием уже есть");
}
}
}
}