#include "changeprocessor.h"
#include "db/dbchangeprocessor.h"
#include "core/eventbus.h"
#include "core/events.h"
#include <QDebug>

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

void ChangeProcessor::processMailItemAdded(const QString &accountId, const MailItem &item)
{
    using namespace WinoMail::Events;
    
    MailItemAddedEvent event;
    event.item = item;
    EVENT_BUS.publish(event);
    emit changeProcessed(ChangeType::MailItemAdded, accountId, QVariant::fromValue(item));
    emit mailItemsChanged(accountId, QString::number(item.folderId()));
}

void ChangeProcessor::processMailItemUpdated(const QString &accountId, const MailItem &item)
{
    using namespace WinoMail::Events;
    
    MailItemUpdatedEvent event;
    event.item = item;
    EVENT_BUS.publish(event);
    emit changeProcessed(ChangeType::MailItemUpdated, accountId, QVariant::fromValue(item));
}

void ChangeProcessor::processMailItemDeleted(const QString &accountId, const QString &mailItemId)
{
    using namespace WinoMail::Events;
    
    MailItemRemovedEvent event;
    event.itemUid = mailItemId;
    event.folderId = accountId.toInt();
    EVENT_BUS.publish(event);
    emit changeProcessed(ChangeType::MailItemDeleted, accountId, mailItemId);
}

void ChangeProcessor::processFolderAdded(const QString &accountId, const Folder &folder)
{
    Q_UNUSED(accountId);
    qDebug() << "[ChangeProcessor] Folder added:" << folder.name();
    emit changeProcessed(ChangeType::FolderAdded, accountId, QVariant::fromValue(folder));
}

void ChangeProcessor::processFolderDeleted(const QString &accountId, const QString &folderId)
{
    Q_UNUSED(accountId);
    qDebug() << "[ChangeProcessor] Folder deleted:" << folderId;
    emit changeProcessed(ChangeType::FolderDeleted, accountId, folderId);
}

void ChangeProcessor::processAccountAdded(const Account &account)
{
    qDebug() << "[ChangeProcessor] Account added:" << account.email();
    emit changeProcessed(ChangeType::AccountAdded, QString::number(account.id()), QVariant::fromValue(account));
}

void ChangeProcessor::processAccountRemoved(const QString &accountId)
{
    qDebug() << "[ChangeProcessor] Account removed:" << accountId;
    emit changeProcessed(ChangeType::AccountDeleted, accountId, accountId);
}
