// SPDX-FileCopyrightText: 2023 g10 code Gmbh
// SPDX-Contributor: Carl Schwan <carl.schwan@gnupg.com>
// SPDX-License-Identifier: GPL-2.0-or-later

#include "composerwindowfactory.h"
#include "draft/draftmanager.h"
#include "editor/composerwindow.h"

ComposerWindowFactory::ComposerWindowFactory() = default;

ComposerWindowFactory &ComposerWindowFactory::self()
{
    static ComposerWindowFactory instance;
    return instance;
}

ComposerWindow *ComposerWindowFactory::create(const QString &fromAddress, const QString &name, const QByteArray &bearerToken)
{
    if (m_inactiveWindow) {
        auto window = m_inactiveWindow;
        m_inactiveWindow = nullptr;
        window->reset(fromAddress, name, bearerToken);
        return window;
    }

    auto window = new ComposerWindow(fromAddress, name, bearerToken);
    QObject::connect(window, &ComposerWindow::initialized, window, [window, this]() {
        const auto key = m_activeWindows.key(window);
        if (!key.isEmpty()) {
            m_activeWindows.remove(key);
        }
        m_activeWindows[window->mailId()] = window;
    });
    return window;
}

void ComposerWindowFactory::restoreAutosave(const QString &email, const QString &displayName, const QByteArray &bearerToken)
{
    const auto &autosaves = DraftManager::self().autosaves();
    for (const auto &autosave : autosaves) {
        if (!m_activeWindows.contains(autosave.id())) {
            auto dialog = create(email, displayName, bearerToken);
            dialog->setMessage(autosave.mime());
            dialog->setMailId(autosave.id());
            dialog->show();
            dialog->activateWindow();
            dialog->raise();
        }
    }
}

void ComposerWindowFactory::clear(ComposerWindow *composerWindow)
{
    auto close = composerWindow->queryClose();
    if (!close) {
        return;
    }

    if (m_inactiveWindow) {
        composerWindow->deleteLater();
        return;
    }

    m_inactiveWindow = composerWindow;
    m_inactiveWindow->hide();
}
