using MimeKit;
using System.Diagnostics.CodeAnalysis;

namespace EmailProvider {

  public interface IEmailMessageBuilder {
  
  }

  public class EmailMessageBuilder : IEmailMessageBuilder {

    private MimeMessage _mimeMessage;

    public EmailMessageBuilder() => Initialize();

    public EmailMessageBuilder(byte[] bytes) => Initialize(bytes);

    public void Initialize() => _mimeMessage = new MimeMessage();

    public void Initialize(byte[] bytes) {
      using var stream = new MemoryStream(bytes);
      _mimeMessage = new MimeMessage(stream);
    }

    public void AddTos(Dictionary<string, string> tos) {
      foreach (var address in tos)
        _mimeMessage.To.Add(new MailboxAddress(address.Value, address.Key));
    }

    public void AddCcs(Dictionary<string, string> ccs) {
      foreach (var address in ccs)
        _mimeMessage.Cc.Add(new MailboxAddress(address.Value, address.Key));
    }

    public void AddBcs(Dictionary<string, string> bccs) {
      foreach (var address in bccs)
        _mimeMessage.Bcc.Add(new MailboxAddress(address.Value, address.Key));
    }

    public void AddSubject(string subject) => _mimeMessage.Subject = subject;

    public void AddHtmlBody(string htmlBody) {
      var bodyBuilder = new BodyBuilder();
      bodyBuilder.HtmlBody = htmlBody;
      _mimeMessage.Body = bodyBuilder.ToMessageBody();
    }

    public void AddTextBody(string textBody) {
      var bodyBuilder = new BodyBuilder();
      bodyBuilder.TextBody = textBody;
      _mimeMessage.Body = bodyBuilder.ToMessageBody();
    }

    public byte [] Build() {
      using var stream = new MemoryStream();
      _mimeMessage.WriteTo(stream);
      return stream.ToArray();
    }
  }
}
