#include "synchronizerprovider.h"
#include "services/gmail/gmailsynchronizer.h"
#include "services/outlook/outlooksynchronizer.h"
#include "services/imap/imapsynchronizer.h"
#include <QDebug>

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

SynchronizerProvider& SynchronizerProvider::instance()
{
    static SynchronizerProvider instance;
    return instance;
}

Synchronizer* SynchronizerProvider::getSynchronizer(const QString &accountId)
{
    return m_synchronizers.value(accountId, nullptr);
}

void SynchronizerProvider::registerSynchronizer(const QString &accountId, Synchronizer *sync)
{
    if (sync) {
        m_synchronizers[accountId] = sync;
        qDebug() << "[SynchronizerProvider] Registered synchronizer for account:" << accountId;
    }
}

void SynchronizerProvider::unregisterSynchronizer(const QString &accountId)
{
    if (m_synchronizers.contains(accountId)) {
        Synchronizer *sync = m_synchronizers.take(accountId);
        sync->deleteLater();
        qDebug() << "[SynchronizerProvider] Unregistered synchronizer for account:" << accountId;
    }
}

Synchronizer* SynchronizerProvider::createSynchronizer(const QString &accountId, const QString &providerType)
{
    if (m_synchronizers.contains(accountId)) {
        qDebug() << "[SynchronizerProvider] Already has synchronizer for" << accountId;
        return m_synchronizers[accountId];
    }

    Synchronizer *sync = nullptr;
    
    if (providerType == "gmail" || providerType == "google") {
        sync = new GmailSynchronizer(this);
    } else if (providerType == "outlook" || providerType == "microsoft") {
        sync = new OutlookSynchronizer(this);
    } else if (providerType == "imap") {
        sync = new ImapSynchronizer(this);
    } else {
        qWarning() << "[SynchronizerProvider] Unknown provider type:" << providerType;
        return nullptr;
    }

    registerSynchronizer(accountId, sync);
    qDebug() << "[SynchronizerProvider] Created synchronizer for account:" << accountId 
             << "type:" << providerType;
    return sync;
}

bool SynchronizerProvider::hasSynchronizer(const QString &accountId) const
{
    return m_synchronizers.contains(accountId);
}

QStringList SynchronizerProvider::activeAccountIds() const
{
    return m_synchronizers.keys();
}

#include "synchronizerprovider.moc"
