using Microsoft.AspNetCore.Identity.UI.Services;
using MailKit.Net.Smtp;
using MailKit;
using MimeKit;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;

namespace MultipleChoiceTrainer.Services
{
    public class EmailSender : IEmailSender
    {
        public Task SendEmailAsync(string email, string subject, string htmlMessage)
        {
            var allowedDomains = new List<string>() { "rheaktionen.de", "rhetro.de", "tokk.de", "schertel.info" };
            if(string.IsNullOrEmpty(email) || !email.Contains("@"))
            {
                return Task.Run(() => System.Threading.Thread.Sleep(0));
            }

            if(!allowedDomains.Any(e => e.ToLower().Equals(email.Split("@").Last().ToLower())))
            {
                return Task.Run(() => System.Threading.Thread.Sleep(0));
            }

            var message = new MimeMessage();
            message.From.Add(new MailboxAddress("Multiple Choice Traier", "noreply@tokk.de"));  
            message.To.Add(MailboxAddress.Parse(email));
            message.Subject = subject;

            message.Body = new TextPart("html")
            {
                Text = htmlMessage
            };

            using (var client = new SmtpClient())
            {
                client.Connect("mx1.tokk-management.de", 465, true);
                client.Authenticate("noreply@tokk.de", "5ue9iN8JgfNqLH3vgrPi");

                client.Send(message);

                return Task.Run(() => System.Threading.Thread.Sleep(0));
            }
        }
    }
}
