using DocumentFormat.OpenXml.Drawing;
using Microsoft.Extensions.Logging;
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.BusinessLogicsContracts;
using SecuritySystemContracts.SearchModels;
using SecuritySystemContracts.StoragesContracts;
using SecuritySystemContracts.ViewModels;

namespace SecuritySystemBusinessLogic.BusinessLogics
{
    public class MessageInfoLogic : IMessageInfoLogic
    {
        private readonly ILogger _logger;
        private readonly IMessageInfoStorage _messageInfoStorage;
        private readonly IClientLogic _clientLogic;
        public MessageInfoLogic(ILogger<MessageInfoLogic> logger, IMessageInfoStorage messageInfoStorage, IClientLogic clientLogic)
        {
            _logger = logger;
            _messageInfoStorage = messageInfoStorage;
            _clientLogic = clientLogic;
        }

        public bool Create(MessageInfoBindingModel model)
        {
            if (!CheckModelIsValid(model))
            {
                return false;
            }
            var client = _clientLogic.ReadElement(new ClientSearchModel { Email = model.SenderName });
            if (client != null)
            {
                model.ClientId = client.Id;
            }
            if (_messageInfoStorage.Insert(model) == null)
            {
                _logger.LogWarning("Insert operation failed");
                return false;
            }
            return true;
        }

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

        private bool CheckModelIsValid(MessageInfoBindingModel model, bool withParams = true)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }
            if (!withParams)
            {
                return true;
            }
            _logger.LogInformation("MessageInfo. MessageId: {MessageId}", model.MessageId);
            var element = _messageInfoStorage.GetElement(new MessageInfoSearchModel
            {
                MessageId = model.MessageId
            });
            if (element != null)
            {
                _logger.LogDebug("Пиьсмо с таким идентификатором уже есть");
                return false;
            }
            return true;
        }
    }
}
