#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());
        QString translatedSelectAll = tr("Select All");

        if(str.contains(tr("Undo"))) {
            action->setEnabled(canUndo);
         }
        else if(str.contains(tr("Redo"))) {
            action->setEnabled(canRedo);
        }
        // 复制、剪切、删除 - 需要有选中文本才能启用
        else if(str.contains("Copy", Qt::CaseInsensitive) || str.contains("复制") ||
                str.contains("Cut", Qt::CaseInsensitive) || str.contains("剪切") ||
                str.contains("Delete", Qt::CaseInsensitive) || str.contains("删除")) {
            action->setEnabled(hasSelection);
            qDebug() << "  -> Copy/Cut/Delete, enabled:" << hasSelection;
        }
        else if(str.contains(translatedSelectAll, Qt::CaseInsensitive) ||
                str.contains("Select All", Qt::CaseInsensitive) ||
                str.contains("全选") ||
                str.contains("selectall", Qt::CaseInsensitive)) {
            // 修复：只要有文本就应该可以全选，不管当前是否有选中的文本
            action->setEnabled(canSelectAll);
            qDebug() << "Select All menu item - str:" << str << "canSelectAll:" << 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();
    result = result.trimmed();

    // 统一处理全选文本
    if (result.contains("select", Qt::CaseInsensitive) &&
        result.contains("all", Qt::CaseInsensitive)) {
        result = "Select All";  // 统一返回标准格式
    }

    return result;
}
