using Amazon;
using Amazon.SimpleEmail;
using Amazon.SimpleEmail.Model;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Knoks.Framework.Services
{
    public class AwsEmailService : IEmailService
    {
        private ILogger<AwsEmailService> _logger;
        private AwsEmailSettings _settings;
        private RegionEndpoint _regionEndpoint { get; }

        public AwsEmailService(ILogger<AwsEmailService> logger, AwsEmailSettings settings)
        {
            _logger = logger;
            _settings = settings;
            _regionEndpoint = RegionEndpoint.EnumerableAllRegions.Single(r => r.SystemName == settings.RegionSystemName);
        }

        public async Task<bool> SendText(string subject, string body, string fromАddress, params string[] toАddresses)
        {
            return await SendMsg(subject, body, false, fromАddress, new EmailDestinationtoАddresses(toАddresses));
        }

        public async Task<bool> SendText(string subject, string body, string fromАddress, EmailDestinationtoАddresses аddresses)
        {
            return await SendMsg(subject, body, false, fromАddress, аddresses);
        }

        public async Task<bool> SendHtml(string subject, string body, string fromАddress, params string[] toАddresses)
        {
            return await SendMsg(subject, body, true, fromАddress, new EmailDestinationtoАddresses(toАddresses));
        }

        public async Task<bool> SendHtml(string subject, string body, string fromАddress, EmailDestinationtoАddresses аddresses)
        {
            return await SendMsg(subject, body, true, fromАddress, аddresses);
        }

        private async Task<bool> SendMsg(string subject, string body, bool isBodyHtml, string fromАddress, EmailDestinationtoАddresses аddresses)
        {
            using (var client = new AmazonSimpleEmailServiceClient(_settings.AccessKeyId, _settings.SecretAccessKey, _regionEndpoint))
            {
                try
                {
                    fromАddress = fromАddress ?? _settings.FromEmail;
                    _logger.LogDebug("Send {0} email - From: {1}; To: {2}", isBodyHtml ? "html" : "text", fromАddress, string.Join(",", аddresses.ToAddresses));

                    var response = await client.SendEmailAsync(new SendEmailRequest
                    {
                        Source = fromАddress,

                        Destination = new Destination
                        {
                            ToAddresses = new List<string>(аddresses.ToAddresses),
                            CcAddresses = аddresses.CcAddresses == null ? null : new List<string>(аddresses.CcAddresses),
                            BccAddresses = аddresses.BccAddresses == null ? null : new List<string>(аddresses.BccAddresses)
                        },

                        Message = new Message
                        {
                            Subject = new Amazon.SimpleEmail.Model.Content(subject),
                            Body = (isBodyHtml ? new Body { Html = new Amazon.SimpleEmail.Model.Content(body) } : new Body { Text = new Amazon.SimpleEmail.Model.Content(body) })
                        }
                    });

                    return true;
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.Message);
                    return false;
                }
            }
        }
    }
}
