#include "texteditmenuprovider.h"
#include <QMenu>
#include <QQuickWindow>
#include <QDebug>
#include <QAction>
#include <QGuiApplication>
#include <QRegularExpression>
#include <QTimer>

TextEditMenuProvider::TextEditMenuProvider(QObject *parent)
    : QObject(parent)
{
    m_dummyTextEdit = new QTextEdit();
    m_contextMenu = m_dummyTextEdit->createStandardContextMenu();
    // 连接菜单动作到信号
    foreach (QAction *action, m_contextMenu->actions()) {
        connect(action, &QAction::triggered, this, [this, action](){
            emit menuActionTriggered(getActionText(action->text()));
        });
    }
}

void TextEditMenuProvider::showContextMenu(QQuickItem *item, bool canUndo, bool canRedo, bool hasSelection, bool canSelectAll)
{
    if (!item || !item->window()) return;
    // 更新菜单项状态
    m_contextMenu = m_dummyTextEdit->createStandardContextMenu();
    // 连接菜单动作到信号
    foreach (QAction *action, m_contextMenu->actions()) {
        QString str = getActionText(action->text());
        if(str.contains(tr("Undo"))) {
            action->setEnabled(canUndo);
         }
        else if(str.contains(tr("Redo"))) {
            action->setEnabled(canRedo);
        }
        else if(str.contains(tr("Copy"))||str.contains(tr("Cut"))||str.contains(tr("Delete"))) {
            action->setEnabled(hasSelection);
        }
        else if(str.contains(tr("Select All"))) {
            action->setEnabled(canSelectAll);
        }
        connect(action, &QAction::triggered, this, [this, action](){
            emit menuActionTriggered(getActionText(action->text()));
        });
    }
    m_contextMenu->exec(QCursor::pos());
    return;
}

QString TextEditMenuProvider::getActionText(QString actionText)
{
    QString result = actionText.remove(QRegularExpression(R"([&]|\(&[^)]*\))")).split("\t").first();
    return result;
}
