using BarContracts.BindingModels; using BarContracts.BusinessLogicsContracts; using BarContracts.SearchModels; using BarContracts.StoragesContracts; using BarContracts.ViewModels; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BarBusinessLogic.BusinessLogics { public class CocktailLogic : ICocktailLogic { private readonly ILogger _logger; private readonly ICocktailStorage _cocktailStorage; public CocktailLogic(ILogger logger, ICocktailStorage cocktailStorage) { _logger = logger; _cocktailStorage = cocktailStorage; } public List? ReadList(CocktailSearchModel? model) { _logger.LogInformation("ReadList. CocktailName:{CocktailName}. Id:{ Id}", model?.CocktailName, model?.Id); var list = model == null ? _cocktailStorage.GetFullList() : _cocktailStorage.GetFilteredList(model); if (list == null) { _logger.LogWarning("ReadList return null list"); return null; } _logger.LogInformation("ReadList. Count:{Count}", list.Count); return list; } public CocktailViewModel? ReadElement(CocktailSearchModel model) { if (model == null) { throw new ArgumentNullException(nameof(model)); } _logger.LogInformation("ReadElement. CocktailName:{CocktailName}.Id:{ Id}", model.CocktailName, model.Id); var element = _cocktailStorage.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(CocktailBindingModel model) { CheckModel(model); if (_cocktailStorage.Insert(model) == null) { _logger.LogWarning("Insert operation failed"); return false; } return true; } public bool Update(CocktailBindingModel model) { CheckModel(model); if (_cocktailStorage.Update(model) == null) { _logger.LogWarning("Update operation failed"); return false; } return true; } public bool Delete(CocktailBindingModel model) { CheckModel(model, false); _logger.LogInformation("Delete. Id:{Id}", model.Id); if (_cocktailStorage.Delete(model) == null) { _logger.LogWarning("Delete operation failed"); return false; } return true; } private void CheckModel(CocktailBindingModel model, bool withParams = true) { if (model == null) { throw new ArgumentNullException(nameof(model)); } if (!withParams) { return; } if (string.IsNullOrEmpty(model.CocktailName)) { throw new ArgumentNullException("Нет названия компонента", nameof(model.CocktailName)); } if (model.Price <= 0) { throw new ArgumentNullException("Цена компонента должна быть больше 0", nameof(model.Price)); } _logger.LogInformation("Cocktail. CocktailName:{CocktailName}.Cost:{ Cost}. Id: { Id}", model.CocktailName, model.Price, model.Id); var element = _cocktailStorage.GetElement(new CocktailSearchModel { CocktailName = model.CocktailName }); if (element != null && element.Id != model.Id) { throw new InvalidOperationException("Компонент с таким названием уже есть"); } } } }