using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VetClinicContracts.BindingModels;
using VetClinicContracts.BusinessLogicsContracts;
using VetClinicContracts.SearchModels;
using VetClinicContracts.StoragesContracts;
using VetClinicContracts.ViewModels;

namespace VetClinicBusinessLogic.BusinessLogics
{
	public class VisitLogic : IVisitLogic
	{
		private readonly ILogger _logger;
		private readonly IVisitStorage _visitStorage;
		public VisitLogic(ILogger<VisitLogic> logger, IVisitStorage visitStorage)
		{
			_logger = logger;
			_visitStorage = visitStorage;
		}

		public List<VisitViewModel>? ReadList(VisitSearchModel? model)
		{
			_logger.LogInformation("ReadList. NameVisit:{NameVisit}. Id:{ Id}", model?.NameVisit, model?.Id);
			var list = model == null ? _visitStorage.GetFullList() :
_visitStorage.GetFilteredList(model);
			if (list == null)
			{
				_logger.LogWarning("ReadList return null list");
				return null;
			}
		
			return list;
		}
		public VisitViewModel? ReadElement(VisitSearchModel model)
		{
			if (model == null)
			{
				throw new ArgumentNullException(nameof(model));
			}
			_logger.LogInformation("ReadElement. NameVisit:{NameVisit}.Id:{ Id}", model.NameVisit, model.Id);
			var element = _visitStorage.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(VisitBindingModel model)
		{
			CheckModel(model);
			if (_visitStorage.Insert(model) == null)
			{
				_logger.LogWarning("Insert operation failed");
				return false;
			}
			return true;
		}

		public bool Update(VisitBindingModel model)
		{
			CheckModel(model);
			if (_visitStorage.Update(model) == null)
			{
				_logger.LogWarning("Update operation failed");
				return false;
			}
			return true;
		}
		public bool Delete(VisitBindingModel model)
		{
			CheckModel(model, false);
			_logger.LogInformation("Delete. Id:{Id}", model.Id);
			if (_visitStorage.Delete(model) == null)
			{
				_logger.LogWarning("Delete operation failed");
				return false;
			}
			return true;
		}

		private void CheckModel(VisitBindingModel model, bool withParams =
true)
		{
			if (model == null)
			{
				throw new ArgumentNullException(nameof(model));
			}
			if (!withParams)
			{
				return;
			}
			if (string.IsNullOrEmpty(model.NameVisit))
			{
				throw new ArgumentNullException("Нет названия визита",
			   nameof(model.NameVisit));
			}
		
			_logger.LogInformation("Medicine. Medicine:{NameVisit}. Id: { Id}", model.NameVisit, model.Id);
			var element = _visitStorage.GetElement(new VisitSearchModel
			{
				NameVisit = model.NameVisit
			});
			if (element != null && element.Id != model.Id)
			{
				throw new InvalidOperationException("Визит с таким названием уже есть");
			}
		}
	}
}
