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

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

#include "askautogeneratetextplugineditorinterface.h"

#include <KActionCollection>
#include <PimAutoGenerateText/AutogenerateConfigureAskManager>
#include <PimAutoGenerateText/AutogenerateConfigureAskMenu>
#include <QAction>
#include <TextAutoGenerateText/TextAutoGenerateDialog>
#include <TextCustomEditor/RichTextEditor>

using namespace Qt::Literals::StringLiterals;
AskAutogenerateTextPluginEditorInterface::AskAutogenerateTextPluginEditorInterface(QObject *parent)
    : MessageComposer::PluginEditorInterface(parent)
    , mAskManager(new AutogenerateConfigureAskManager(this))
{
    setNeedSelectedText(true);
}

AskAutogenerateTextPluginEditorInterface::~AskAutogenerateTextPluginEditorInterface() = default;

void AskAutogenerateTextPluginEditorInterface::createAction(KActionCollection *ac)
{
    auto menu = new AutogenerateConfigureAskMenu(mAskManager, this);
    connect(this, &AskAutogenerateTextPluginEditorInterface::refreshMenu, menu, &AutogenerateConfigureAskMenu::slotRefreshMenu);
    ac->addAction(u"editor_ask_ia"_s, menu);
    connect(menu, &AutogenerateConfigureAskMenu::askRequested, this, &AskAutogenerateTextPluginEditorInterface::slotAskRequested);
    const MessageComposer::PluginActionType type(menu, MessageComposer::PluginActionType::Edit);
    setActionType(type);
}

void AskAutogenerateTextPluginEditorInterface::slotAskRequested(const QString &msg)
{
    mAskMsg = msg;
    Q_EMIT emitPluginActivated(this);
}

void AskAutogenerateTextPluginEditorInterface::exec()
{
    auto dlg = new TextAutoGenerateText::TextAutoGenerateDialog(parentWidget());
    dlg->setAttribute(Qt::WA_DeleteOnClose);
    dlg->show();
    QTextCursor textCursor = richTextEditor()->textCursor();
    const QString selectedText = textCursor.selectedText();
    const TextAutoGenerateText::TextAutoGenerateManager::AskMessageInfo info{.message = u"%1: \"%2\""_s.arg(mAskMsg, selectedText),
                                                                             .attachments = {},
                                                                             .tools = {}};
    dlg->ask(info);
}

void AskAutogenerateTextPluginEditorInterface::slotRefreshMenu()
{
    Q_EMIT refreshMenu();
}

#include "moc_askautogeneratetextplugineditorinterface.cpp"
