/*
   SPDX-FileCopyrightText: 2025-2026 Laurent Montel <montel@kde.org>

   SPDX-License-Identifier: GPL-2.0-or-later
*/

#include "autogenerateconfigureaskmenu.h"
#include "autogenerateconfigureaskdialog.h"
#include "autogenerateconfigureaskmanager.h"

#include <KLocalizedString>
#include <QMenu>

AutogenerateConfigureAskMenu::AutogenerateConfigureAskMenu(AutogenerateConfigureAskManager *manager, QObject *parent)
    : KActionMenu{parent}
    , mManager(manager)
{
    mManager->load();
    setText(i18n("Ask AI…"));
    // mMenu->setIcon(QIcon::fromTheme(QStringLiteral("document-share")));
    initializeMenu();
}

AutogenerateConfigureAskMenu::~AutogenerateConfigureAskMenu() = default;

void AutogenerateConfigureAskMenu::initializeMenu()
{
    const auto infos = mManager->askInfos();
    for (const AutogenerateConfigureAskInfo &info : infos) {
        if (info.enabled()) {
            auto action = new QAction(info.title(), this);
            const QString promptText = info.text();
            connect(action, &QAction::triggered, this, [promptText, this]() {
                Q_EMIT askRequested(promptText);
            });
            addAction(action);
        }
    }
    auto configureAction = new QAction(QIcon::fromTheme(QStringLiteral("configure")), i18nc("@action", "Configure…"), this);
    connect(configureAction, &QAction::triggered, this, &AutogenerateConfigureAskMenu::slotConfigure);
    addSeparator();
    addAction(configureAction);
}

void AutogenerateConfigureAskMenu::slotConfigure()
{
    AutogenerateConfigureAskDialog dlg(mParentWidget);
    dlg.setAskInfos(mManager->askInfos());
    if (dlg.exec()) {
        mManager->setInfos(dlg.askInfos());
        mManager->save();
        slotRefreshMenu();
    }
}

QString AutogenerateConfigureAskMenu::selectedText() const
{
    return mSelectedText;
}

void AutogenerateConfigureAskMenu::setSelectedText(const QString &newSelectedText)
{
    mSelectedText = newSelectedText;
}

void AutogenerateConfigureAskMenu::slotRefreshMenu()
{
    menu()->clear();
    initializeMenu();
}

QWidget *AutogenerateConfigureAskMenu::parentWidget() const
{
    return mParentWidget;
}

void AutogenerateConfigureAskMenu::setParentWidget(QWidget *newParentWidget)
{
    mParentWidget = newParentWidget;
}

#include "moc_autogenerateconfigureaskmenu.cpp"
