using BookShopContracts.BindingModels; using BookShopContracts.BusinessLogicsContracts; using BookShopContracts.SearchModels; using BookShopContracts.StoragesContracts; using BookShopContracts.ViewModels; using BookShopDataModels.Models; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BookShopBusinessLogic.BusinessLogics { public class GenreLogic : IGenreLogic { private readonly ILogger _logger; private readonly IGenreStorage _genreStorage; public GenreLogic(ILogger logger, IGenreStorage genreStorage) { _logger = logger; _genreStorage = genreStorage; } public bool Create(GenreBindingModel model) { CheckModel(model); if (_genreStorage.Insert(model) == null) { _logger.LogWarning("Insert operation failed"); return false; } return true; } public bool Delete(GenreBindingModel model) { CheckModel(model, false); _logger.LogInformation("Delete. Id: {Id}", model.Id); if (_genreStorage.Delete(model) == null) { _logger.LogWarning("Delete operation failed"); return false; } return true; } public GenreViewModel? ReadElement(GenreSearchModel model) { if (model == null) { throw new ArgumentNullException(nameof(model)); } _logger.LogInformation("ReadElement. GenreName: {GenreName}. Id: {Id}.", model.GenreName, model.Id); var element = _genreStorage.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? ReadList(GenreSearchModel? model) { _logger.LogInformation("ReadList. GenreName: {GenreName}. Id: {Id}.", model?.GenreName, model?.Id); var list = model == null ? _genreStorage.GetFullList() : _genreStorage.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(GenreBindingModel model) { CheckModel(model); if (_genreStorage.Update(model) == null) { _logger.LogWarning("Update operation failed"); return false; } return true; } private void CheckModel(GenreBindingModel model, bool withParams = true) { if (model == null) { throw new ArgumentNullException(nameof(model)); } if (!withParams) { return; } if (string.IsNullOrEmpty(model.GenreName)) { throw new ArgumentNullException("Нет названия жанра", nameof(model.GenreName)); } _logger.LogInformation("Genre. GenreName: {GenreName}. Id: {Id}.", model.GenreName, model.Id); var element = _genreStorage.GetElement(new GenreSearchModel { GenreName = model.GenreName }); if (element != null && element.Id != model.Id) { throw new InvalidOperationException("Такой жанр уже есть"); } } } }