using VetClinicContracts.BindingModels;
using VetClinicContracts.BusinessLogicsContracts;
using VetClinicContracts.SearchModels;
using VetClinicContracts.StoragesContracts;
using VetClinicContracts.ViewModels;
using Microsoft.Extensions.Logging;

namespace VetClinicBusinessLogic.BusinessLogics
{
	public class AnimalLogic : IAnimalLogic
	{
		private readonly ILogger _logger;
		private readonly IAnimalStorage _animalStorage;
		public AnimalLogic(ILogger<AnimalLogic> logger, IAnimalStorage animalStorage)
		{
			_logger = logger;
			_animalStorage = animalStorage;
		}
		public List<AnimalViewModel>? ReadList(AnimalSearchModel? model)
		{
			_logger.LogInformation("ReadList. Id:{ Id}", model?.Id);
			var list = model == null ? _animalStorage.GetFullList() : _animalStorage.GetFilteredList(model);
			if (list == null)
			{
				_logger.LogWarning("ReadList return null list");
				return null;
			}
			
			return list;
		}
		public AnimalViewModel? ReadElement(AnimalSearchModel model)
		{
			if (model == null)
			{
				throw new ArgumentNullException(nameof(model));
			}
			_logger.LogInformation("ReadList. AnimalName:{AnimalName}. Family {Family}. Id:{Id}", model.AnimalName, model?.Family, model?.Id);

			var element = _animalStorage.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 CreateAnimal(AnimalBindingModel model)
		{
			CheckModel(model);
			
			if (_animalStorage.Insert(model) == null)
			{
				_logger.LogWarning("Insert operation failed");
				return false;
			}
			return true;
		}

		public bool UpdateAnimal(AnimalBindingModel model)
		{
			CheckModel(model);
			if (_animalStorage.Update(model) == null)
			{
				_logger.LogWarning("Update operation failed");
				return false;
			}
			return true;
		}

		public bool DeleteAnimal(AnimalBindingModel model)
		{
			CheckModel(model, false);
			_logger.LogInformation("Delete. Id:{Id}", model.Id);
			if (_animalStorage.Delete(model) == null)
			{
				_logger.LogWarning("Delete operation failed");
				return false;
			}
			return true;
		}
		private void CheckModel(AnimalBindingModel model, bool withParams = true)
		{
			if (model == null)
			{
				throw new ArgumentNullException(nameof(model));
			}
			if (!withParams)
			{
				return;
			}
			if (model.AnimalName == "")
			{
				throw new ArgumentNullException("Имя не должно быть пустым", nameof(model.AnimalName));
			}
			if (model.AdminId < 0)
			{
				throw new ArgumentNullException("Некорректный идентификатор у клиента", nameof(model.AdminId));
			}
			
			var element = _animalStorage.GetElement(new AnimalSearchModel
			{
				Id = model.Id
			});
			
		}
	}
}