using CarShowroomContracts.BusinessLogic; using CarShowroomContracts.StorageContracts; using CarShowroomDataModels.Dtos; using CarShowroomDataModels.SearchModel; using CarShowroomDataModels.Views; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CarShowroomBusinessLogic.BusinessLogic { public class ModelLogic : IModelLogic { private readonly IModelStorage _modelStorage; public ModelLogic(IModelStorage storage) { _modelStorage = storage; } public List? ReadList(ModelSearch? model) { var list = model == null ? _modelStorage.GetFullList() : _modelStorage.GetFilteredList(model); if (list == null) { return null; } return list; } public ModelView? ReadElement(ModelSearch model) { if (model == null) { throw new ArgumentNullException(nameof(model)); } var element = _modelStorage.GetElement(model); if (element == null) { return null; } return element; } public bool Create(ModelDto model) { CheckModel(model); if (_modelStorage.Insert(model) == null) { return false; } return true; } public bool Update(ModelDto model) { CheckModel(model); if (_modelStorage.Update(model) == null) { return false; } return true; } public bool Delete(ModelDto model) { CheckModel(model, false); if (_modelStorage.Delete(model) == null) { return false; } return true; } private void CheckModel(ModelDto model, bool withParams = true) { if (model == null) throw new ArgumentNullException(nameof(model)); if (!withParams) return; if (string.IsNullOrEmpty(model.Name)) throw new InvalidOperationException(); if (model.MakeId < 0) throw new InvalidOperationException(); if (model.Price < 0) throw new InvalidOperationException(); var element = _modelStorage.GetElement(new ModelSearch { Name = model.Name, }); if (element != null && element.Id != model.Id) throw new InvalidOperationException(); } } }