using Microsoft.Extensions.Logging; using STOContracts.BindingModels; using STOContracts.BusinessLogicsContracts; using STOContracts.SearchModels; using STOContracts.StorageContracts; using STOContracts.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ShipyardBusinessLogic { public class CarLogic: ICarLogic { private readonly ILogger _logger; private readonly ICarStorage _CarStorage; public CarLogic(ILogger logger, ICarStorage CarStorage) { _logger = logger; _CarStorage = CarStorage; } public List? ReadList(CarSearchModel? model) { _logger.LogInformation("ReadList. CarNumber:{CarNumber}. Id:{ Id}", model?.CarNumber, model?.Id); var list = model == null ? _CarStorage.GetFullList() : _CarStorage.GetFilteredList(model); if (list == null) { _logger.LogWarning("ReadList return null list"); return null; } _logger.LogInformation("ReadList. Count:{Count}", list.Count); return list; } public CarViewModel? ReadElement(CarSearchModel model) { if (model == null) { throw new ArgumentNullException(nameof(model)); } _logger.LogInformation("ReadElement. CarNumber:{CarNumber}.Id:{ Id}", model.CarNumber, model.Id); var element = _CarStorage.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(CarBindingModel model) { CheckModel(model); if (_CarStorage.Insert(model) == null) { _logger.LogWarning("Insert operation failed"); return false; } return true; } public bool Update(CarBindingModel model) { CheckModel(model); if (_CarStorage.Update(model) == null) { _logger.LogWarning("Update operation failed"); return false; } return true; } public bool Delete(CarBindingModel model) { CheckModel(model, false); _logger.LogInformation("Delete. Id:{Id}", model.Id); if (_CarStorage.Delete(model) == null) { _logger.LogWarning("Delete operation failed"); return false; } return true; } private void CheckModel(CarBindingModel model, bool withParams = true) { if (model == null) { throw new ArgumentNullException(nameof(model)); } if (!withParams) { return; } if (string.IsNullOrEmpty(model.CarNumber)) { throw new ArgumentNullException("Нет гос номера автомобиля", nameof(model.CarNumber)); } if (string.IsNullOrEmpty(model.CarBrand)) { throw new ArgumentNullException("Нет марки автомобиля", nameof(model.CarNumber)); } if (string.IsNullOrEmpty(model.CarModel)) { throw new ArgumentNullException("Нет модели автомобиля", nameof(model.CarNumber)); } _logger.LogInformation("Car. Car:{Car}. Id: { Id}", model.CarNumber, model.Id); var element = _CarStorage.GetElement(new CarSearchModel { CarNumber = model.CarNumber }); if (element != null && element.Id != model.Id) { throw new InvalidOperationException("авто с таким номером уже есть"); } } } }