// SPDX-FileCopyrightText: 2024 g10 Code GmbH
// SPDX-FileContributor: Carl Schwan <carl@carlschwan.eu>
// SPDX-License-Identifier: GPL-2.0-or-later

#include "configuredialog.h"

#include <QAction>

#include <KConfig>
#include <KConfigGroup>
#include <KLocalizedString>
#include <KPageWidgetModel>
#include <KSharedConfig>
#include <QAction>

#include "conf/generalconfigurationpage.h"
#include "conf/rootfoldersconfigurationpage.h"
#include "conf/templateconfigurationpage.h"

ConfigureDialog::ConfigureDialog(RootFoldersManager *rootFoldersManager, QWidget *parent)
    : GpgPassPageConfigDialog(parent)
{
    setWindowTitle(i18nc("@title:window", "Configure"));
    resize(900, 560);

    m_generalPage = addModule(i18n("General"), {}, QStringLiteral("settings-configure-symbolic"), {}, new GpgPass::Config::GeneralConfigurationPage(this));

    auto addStoreAction = new QAction(QIcon::fromTheme(QStringLiteral("list-add-symbolic")), i18nc("@action:intoolbar", "Add Password Store"));
    m_passwordStoresPage = addModule(i18n("Password Stores"),
                                     {},
                                     QStringLiteral("document-open-folder-symbolic"),
                                     {addStoreAction},
                                     new GpgPass::Config::RootFoldersConfigurationPage(rootFoldersManager, addStoreAction, this));

    m_templatePage = addModule(i18n("Templates"), {}, QStringLiteral("template-symbolic"), {}, new GpgPass::Config::TemplateConfigurationPage(this));

    // We store the minimum size of the dialog on hide, because otherwise
    // the KCMultiDialog starts with the size of the first kcm, not
    // the largest one. This way at least after the first showing of
    // the largest kcm the size is kept.
    const KConfigGroup geometry(KSharedConfig::openStateConfig(), QStringLiteral("Geometry"));
    const int width = geometry.readEntry("ConfigureDialogWidth", 0);
    const int height = geometry.readEntry("ConfigureDialogHeight", 0);
    if (width != 0 && height != 0) {
        setMinimumSize(width, height);
    }
}

void ConfigureDialog::openPage(Page page)
{
    switch (page) {
    case Page::None:
        return;
    case Page::General:
        setCurrentPage(m_generalPage);
        return;
    case Page::PasswordsStore:
        setCurrentPage(m_passwordStoresPage);
        return;
    case Page::Template:
        setCurrentPage(m_templatePage);
        return;
    }
}

void ConfigureDialog::hideEvent(QHideEvent *e)
{
    const QSize minSize = minimumSizeHint();
    KConfigGroup geometry(KSharedConfig::openStateConfig(), QStringLiteral("Geometry"));
    geometry.writeEntry("ConfigureDialogWidth", minSize.width());
    geometry.writeEntry("ConfigureDialogHeight", minSize.height());
    GpgPassPageConfigDialog::hideEvent(e);
}

#include "moc_configuredialog.cpp"
