using System.Threading.Tasks;
using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;

namespace BoredCareers.Services {
    public partial class EmailService {

        public Dictionary<string, DateTime> _SentEmails = new Dictionary<string, DateTime>();
        
        public string EmailServer = "";
        public string EmailAddress = "";
        public string EmailPassword = "";
        public int EmailPort;

        public EmailService( string _EmailServer, int _EmailPort, string _EmailAddress, string _EmailPassword ) {
            EmailServer = _EmailServer;
            EmailPort = _EmailPort;
            EmailAddress = _EmailAddress;
            EmailPassword = _EmailPassword;
        }

        public async Task<string> Send(string Destination, string Subject, string Body) {
            try {
                MimeMessage message = new MimeMessage();
                message.From.Add(new MailboxAddress(EmailAddress.Split('@')[0], EmailAddress));
                message.To.Add(new MailboxAddress(Destination.Split('@')[0], Destination));
                message.Subject = Subject;

                BodyBuilder messageBody = new BodyBuilder();
                messageBody.HtmlBody = Body;

                message.Body = messageBody.ToMessageBody();

                using (SmtpClient client = new SmtpClient()) {
                    await client.ConnectAsync(EmailServer, EmailPort);
                    client.Authenticate(new SaslMechanismLogin(EmailAddress, EmailPassword));
                    string serverResponse = await client.SendAsync(message);
                    await client.DisconnectAsync(true);
                    return serverResponse;
                }
            } catch (Exception e) {
                    return "An Error Has Occurred Sending Email : " + e.ToString();
                }
        }

    }
}