using BarContracts.BindingModels;
using BarContracts.BusinessLogicContracts;
using BarContracts.SearchModels;
using BarContracts.StoragesContracts;
using BarContracts.ViewModels;
using Microsoft.Extensions.Logging;

namespace BarBusinessLogic.BusinessLogics
{
	public class MessageInfoLogic : IMessageInfoLogic
	{
		private readonly ILogger _logger;
		
		private readonly IMessageInfoStorage _messageInfoStorage;
		private readonly IClientStorage _clientStorage;

		public MessageInfoLogic(ILogger<MessageInfoLogic> Logger, IMessageInfoStorage MessageInfoStorage, IClientStorage ClientStorage)
		{
			_logger = Logger;
			_messageInfoStorage = MessageInfoStorage;
			_clientStorage = ClientStorage;
		}

		public List<MessageInfoViewModel>? ReadList(MessageInfoSearchModel? Model)
		{
			_logger.LogDebug("ReadList. MessageId: {MessageId}, ClientId: {ClientId}", Model?.MessageId, Model?.ClientId);

			var Result = Model == null ? _messageInfoStorage.GetFullList() : _messageInfoStorage.GetFilteredList(Model);

			_logger.LogDebug("ReadList result. Count: {Count}", Result.Count);
			return Result;
		}

		public bool Create(MessageInfoBindingModel Model)
		{
			try {
				CheckModel(Model);

				if (_messageInfoStorage.Insert(Model) == null)
				{
					_logger.LogWarning("Insert operation failed");
					return false;
				}
			}
			catch  { }
			return true;
			
		}

		private void CheckModel(MessageInfoBindingModel Model, bool WithParams = true)
		{
			if (Model == null)
				throw new ArgumentNullException(nameof(Model));

			if (!WithParams)
				return;

			if (string.IsNullOrEmpty(Model.MessageId))
				throw new ArgumentNullException("Не указан id сообщения", nameof(Model.MessageId));

			if (string.IsNullOrEmpty(Model.SenderName))
				throw new ArgumentNullException("Не указао почта", nameof(Model.SenderName));

			if (string.IsNullOrEmpty(Model.Subject))
				throw new ArgumentNullException("Не указана тема", nameof(Model.Subject));

			if (string.IsNullOrEmpty(Model.Body)) 
				throw new ArgumentNullException("Не указан текст сообщения", nameof(Model.Subject));

			_logger.LogInformation("MessageInfo. MessageId: {MessageId}. SenderName: {SenderName}. Subject: {Subject}. Body: {Body}", 
				Model.MessageId, Model.SenderName, Model.Subject, Model.Body);
			
			var Element = _clientStorage.GetElement(new ClientSearchModel
			{
				Email = Model.SenderName
			});
			
			if (Element == null)
			{
				_logger.LogWarning("Не удалось найти клиента, отправившего письмо с адреса {Email}", Model.SenderName);
			}
			else
			{
				Model.ClientId = Element.Id;
			}
		}
	}
}
