#include "synchronizerprovider.h"
#include "services/gmail/gmailsynchronizer.h"
#include "services/outlook/outlooksynchronizer.h"
#include "services/imap/imapsynchronizer.h"
#include "services/imap/imapsynchronizer_mailio.h"
#include "services/pop3/pop3synchronizer.h"
#include "services/pop3/pop3synchronizer_mailio.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") {
#if defined(USE_MAILIO_IMAP) && USE_MAILIO_IMAP
        // Use mailio-based IMAP synchronizer (more robust)
        sync = new ImapSynchronizerMailio(this);
#else
        sync = new ImapSynchronizer(this);
#endif
    } else if (providerType == "pop3" || providerType == "pop") {
#if defined(USE_MAILIO_IMAP) && USE_MAILIO_IMAP
        // Use mailio-based POP3 synchronizer
        sync = new Pop3SynchronizerMailio(this);
#else
        sync = new Pop3Synchronizer(this);
#endif
    } 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();
}

