PIbd-32_Artamonova_T.V._COP_2/UniversityBusinessLogic/BusinessLogics/DirectionLogic.cs

109 lines
3.8 KiB
C#
Raw Normal View History

2023-10-28 09:06:35 +04:00
using Microsoft.Extensions.Logging;
using UniversityContracts.BindingModels;
using UniversityContracts.BusinessLogicsContracts;
using UniversityContracts.SearchModels;
using UniversityContracts.StoragesContracts;
using UniversityContracts.ViewModels;
namespace UniversityBusinessLogic.BusinessLogics
{
public class DirectionLogic : IDirectionLogic
{
private readonly ILogger _logger;
private readonly IDirectionStorage _directionStorage;
public DirectionLogic(ILogger<DirectionLogic> logger, IDirectionStorage directionStorage)
{
_logger = logger;
_directionStorage = directionStorage;
}
public void CreateOrUpdate(DirectionBindingModel model)
{
var element = _directionStorage.GetElement(
new DirectionBindingModel
{
Name = model.Name
});
if (element != null && element.Id != model.Id)
{
throw new Exception("Такое направление уже существует");
}
if (model.Id != null)
{
_directionStorage.Update(model);
}
else
{
_directionStorage.Insert(model);
}
}
public bool Delete(DirectionBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_directionStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
public DirectionViewModel? ReadElement(DirectionBindingModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. Name:{Name}. Id:{ Id}", model.Name, model.Id);
var element = _directionStorage.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<DirectionViewModel>? ReadList(DirectionBindingModel? model)
{
_logger.LogInformation("ReadList. Name:{Name}. Id:{ Id}", model?.Name, model?.Id);
var list = model == null ? _directionStorage.GetFullList() : _directionStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
private void CheckModel(DirectionBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.Name))
{
throw new ArgumentNullException("Нет названия направления", nameof(model.Name));
}
_logger.LogInformation("Direction. Name:{Name}. Id: {Id} ", model.Name, model.Id);
var element = _directionStorage.GetElement(new DirectionBindingModel
{
Name = model.Name
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Направление с таким названием уже есть");
}
}
}
}