using BarContracts.BindingModels;
using BarContracts.BusinessLogicContracts;
using Microsoft.Extensions.Logging;

namespace BarBusinessLogic.MailWorker
{
    public abstract class AbstractMailWorker
    {
        protected string _mailLogin = string.Empty;

        protected string _mailPassword = string.Empty;

        protected string _smtpClientHost = string.Empty;

        protected int _smtpClientPort;

        protected string _popHost = string.Empty;

        protected int _popPort;

        private readonly IMessageInfoLogic _messageInfoLogic;

        private readonly ILogger _logger;

        public AbstractMailWorker(ILogger<AbstractMailWorker> Logger, IMessageInfoLogic MessageInfoLogic)
        {
            _logger = Logger;
            _messageInfoLogic = MessageInfoLogic;
        }

        public void MailConfig(MailConfigBindingModel Config)
        {
            _mailLogin = Config.MailLogin;
            _mailPassword = Config.MailPassword;
            _smtpClientHost = Config.SmtpClientHost;
            _smtpClientPort = Config.SmtpClientPort;
            _popHost = Config.PopHost;
            _popPort = Config.PopPort;

            _logger.LogDebug("MailConfig: {Login}, {Password}, {ClientHost}, {ClientPort}, {PopHost}, {PopPort}",
                 _mailLogin, _mailPassword, _smtpClientHost, _smtpClientPort, _popHost, _popPort);
        }

        public async void SendMailAsync(MailSendInfoBindingModel Info)
        {
            if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword))
                return;

            if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0)
                return;

            if (string.IsNullOrEmpty(Info.MailAddress) || string.IsNullOrEmpty(Info.Subject) || string.IsNullOrEmpty(Info.Text))
                return;

            _logger.LogDebug("MailSendAsync: {To}, {Subject}", Info.MailAddress, Info.Subject);

            await SendMailImpl(Info);
        }

        public async void CheckMailAsync()
        {
            if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword))
                return;

            if (string.IsNullOrEmpty(_popHost) || _popPort == 0)
                return;

            if (_messageInfoLogic == null)
                return;

            var List = await ReceiveMailImpl();
            _logger.LogDebug("CheckMailAsync: New mails: {Count}", List.Count);
            
            foreach (var Mail in List)
            {
                _messageInfoLogic.Create(Mail);
            }
        }

        protected abstract Task SendMailImpl(MailSendInfoBindingModel Info);

        protected abstract Task<List<MessageInfoBindingModel>> ReceiveMailImpl();
    }
}
