#include "emailmanager.h"
#include <QDebug>
#include <QFile>
#include <QStandardPaths>
#include "db/dao/mailitemdao.h"
#include "services/mimestorage.h"

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

MailItem EmailManager::getMailItemById(qint64 id) const
{
    const auto item = MailItemDao::findById(id);
    return item.value_or(MailItem());
}

QString EmailManager::getStorageDirectory() const
{
    return QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + QStringLiteral("/mails");
}

QString EmailManager::getEmailHtmlById(qint64 id) const
{
    const auto item = MailItemDao::findById(id);
    if (!item) return QString();
    if (!item->bodyHtml().isEmpty()) return item->bodyHtml();
    if (item->fileId().isEmpty()) return QString();
    MimeStorageService storage;
    ParsedMimeMessage parsed;
    return storage.parseMessage(storage.readEmlFile(item->fileId()), parsed) ? parsed.bodyHtml : QString();
}

QString EmailManager::convertEmlToHtml(const QString& emlFilePath) const
{
    QFile file(emlFilePath);
    if (!file.open(QIODevice::ReadOnly)) return QString();
    MimeStorageService storage;
    ParsedMimeMessage parsed;
    return storage.parseMessage(file.readAll(), parsed) ? parsed.bodyHtml : QString();
}

bool EmailManager::sendEmail(const QString& to, const QString& subject, const QString& body)
{
    Q_UNUSED(to);
    Q_UNUSED(subject);
    Q_UNUSED(body);
    return false;
}
