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 GuidanceLogic : IGuidanceLogic
	{
		private readonly ILogger _logger;
		private readonly IGuidanceStorage _guidanceStorage;

		public GuidanceLogic(ILogger<GuidanceLogic> logger, IGuidanceStorage guidanceStorage)
		{
			_logger = logger;
			_guidanceStorage = guidanceStorage;
		}

		public GuidanceViewModel? ReadElement(GuidanceSearchModel model)
		{
			if (model == null)
			{
				throw new ArgumentNullException(nameof(model));
			}
			_logger.LogInformation("ReadElement. Id:{ Id}", model.Id);
			var element = _guidanceStorage.GetElement(model);
			if (element == null)
			{
				_logger.LogWarning("ReadElement element not found");
				return null;
			}
			_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
			return element;
		}

		public List<GuidanceViewModel>? ReadList(GuidanceSearchModel? model)
		{
			_logger.LogInformation("ReadList. Id:{ Id}", model?.Id);
			var list = model == null ? _guidanceStorage.GetFullList() :
		   _guidanceStorage.GetFilteredList(model);
			if (list == null)
			{
				_logger.LogWarning("ReadList return null list");
				return null;
			}
			_logger.LogInformation("ReadList. Count:{Count}", list.Count);
			return list;
		}

		public bool Create(GuidanceBindingModel model)
		{
			CheckModel(model);
			if (_guidanceStorage.Insert(model) == null)
			{
				_logger.LogWarning("Insert operation failed");
				return false;
			}
			return true;
		}
		public bool Update(GuidanceBindingModel model)
		{
			CheckModel(model);
			if (_guidanceStorage.Update(model) == null)
			{
				_logger.LogWarning("Update operation failed");
				return false;
			}
			return true;
		}
		public bool Delete(GuidanceBindingModel model)
		{
			CheckModel(model, false);
			_logger.LogInformation("Delete. Id:{Id}", model.Id);
			if (_guidanceStorage.Delete(model) == null)
			{
				_logger.LogWarning("Delete operation failed");
				return false;
			}
			return true;
		}
		private void CheckModel(GuidanceBindingModel model, bool withParams =
	   true)
		{
			if (model == null)
			{
				throw new ArgumentNullException(nameof(model));
			}
			if (!withParams)
			{
				return;
			}
			if (string.IsNullOrEmpty(model.Text))
			{
				throw new ArgumentNullException("Нет текста рекомендации",
			   nameof(model.Text));
			}

			_logger.LogInformation("Guidance. Text:{Text}.", model.Text);
		}
	}
}
