115 lines
4.0 KiB
C#
Raw Normal View History

using Microsoft.Extensions.Logging;
using RouteGuideContracts.BindingModels;
using RouteGuideContracts.BusinessLogicContracts;
using RouteGuideContracts.SearchModels;
using RouteGuideContracts.StoragesModels;
using RouteGuideContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RouteGuideBusinessLogic.BusinessLogic
{
public class TransportLogic : ITransportLogic
{
private readonly ILogger _logger;
private readonly ITransportStorage _transportStorage;
public TransportLogic(ILogger<TransportLogic> logger, ITransportStorage transportStorage)
{
_logger = logger;
_transportStorage = transportStorage;
}
public bool Create(TransportBindingModel model)
{
CheckModel(model);
if (_transportStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Delete(TransportBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_transportStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
public TransportViewModel? ReadElement(TransportSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. DriverName:{DriverName}.Id:{ Id}", model.DriverName, model.Id);
var element = _transportStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
public List<TransportViewModel>? ReadList(TransportSearchModel? model)
{
_logger.LogInformation("ReadList. DriverName:{DriverName}.Id:{ Id}", model?.DriverName, model?.Id);
var list = model == null ? _transportStorage.GetFullList() : _transportStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public bool Update(TransportBindingModel model)
{
CheckModel(model);
if (_transportStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
private void CheckModel(TransportBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.DriverName))
{
throw new ArgumentNullException("Нет водителя ", nameof(model.DriverName));
}
_logger.LogInformation("Transport. DriverName:{DriverName}. TransportTypeId:{ TransportTypeId}. Id: { Id}", model.DriverName, model.TransportTypeId, model.Id);
var element = _transportStorage.GetElement(new TransportSearchModel
{
DriverName = model.DriverName
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Transport с таким названием уже есть");
}
}
}
}