#include "emailcomposerbridge.h"
#include <QDebug>
#include <QDateTime>
#include <QUuid>

EmailComposerBridge::EmailComposerBridge(QObject *parent)
    : QObject(parent)
{
}

MailItem EmailComposerBridge::createMailItem(const QString &to, const QString &cc, 
                                              const QString &bcc, const QString &subject,
                                              const QString &body, const QString &accountId,
                                              const QVector<Attachment> &attachments)
{
    MailItem mail;
    mail.setSubject(subject);
    mail.setSender(accountId);
    mail.setTo(to);
    mail.setCc(cc);
    mail.setBcc(bcc);
    mail.setBodyHtml(body);
    mail.setDate(QDateTime::currentDateTime());
    mail.setMessageId(QUuid::createUuid().toString(QUuid::WithoutBraces));
    
    QStringList attList;
    for (const auto &att : attachments) {
        attList.append(att.fileName);
    }
    mail.setAttachments(attList);

    qDebug() << "[EmailComposerBridge] Created mail:" << subject 
             << "to:" << to;

    emit mailReadyToSend(mail);
    return mail;
}

QString EmailComposerBridge::renderBodyToHtml(const QString &plainText) const
{
    QString html = plainText;
    html.replace("&", "&amp;");
    html.replace("<", "&lt;");
    html.replace(">", "&gt;");
    html.replace("\n", "<br>");
    html.replace("\r\n", "<br>");
    return "<html><body>" + html + "</body></html>";
}
