using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;

using Microsoft.AspNetCore.Identity.UI.Services;


namespace CtrlAltAssist.Services;

public class EmailSender : IEmailSender
{
    public async Task SendEmailAsync(string email, string subject, string htmlMessage)
    {
        await SendEmailAsync(email, subject, htmlMessage, "", null);
    }

    public async Task SendEmailAsync(string email, string subject, string htmlMessage,
        string fileName, MemoryStream memoryStream)
    {
        SmtpClient smtp = new SmtpClient("mail85.mailasp.net", 587);
        smtp.UseDefaultCredentials = false;
        smtp.Credentials = new NetworkCredential("mark@spiderink.co.za", "Inkey$123");
        smtp.EnableSsl = true;
        smtp.Timeout = 10000;

        MailAddress from = new MailAddress("mark@spiderink.co.za", "Ctr Alt Assist - Website", System.Text.Encoding.UTF8);

        MailMessage message = new MailMessage();

        message.From = from;

        string[] toAddrs = email.Split(';');

        foreach (string toAddr in toAddrs)
        {
            if (toAddr != "")
                message.To.Add(new MailAddress(toAddr));
        }

        message.Subject = subject;
        message.SubjectEncoding = System.Text.Encoding.UTF8;

        message.IsBodyHtml = true;
        message.Body = htmlMessage;
        message.BodyEncoding = System.Text.Encoding.UTF8;

        if ((fileName != "") && (memoryStream != null))
        {
            memoryStream.Position = 0;
            message.Attachments.Add(new Attachment(memoryStream, fileName));
        }        

        try
        {
            await smtp.SendMailAsync(message);
        }
        catch (Exception e)
        {
            System.Diagnostics.Debug.WriteLine("Failed to send email. " + e.Message);
        }
    }
}
