#include "RasterProcessTool.h"
#include <QObject>
#include "QMergeRasterProcessDialog.h"
#include "QImportGF3StripL1ADataset.h"
#include "QComplex2AmpPhase.h"
#include "QRDOrthProcessClass.h"
#include "QOrthSlrRaster.h"


RasterProcessTool::RasterProcessTool(QWidget *parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);

    QObject::connect(this, SIGNAL(addBoxToolItemSIGNAL(QToolAbstract*)), this, SLOT(addBoxToolItemSLOT(QToolAbstract*)));
}

RasterProcessTool::~RasterProcessTool()
{}

void RasterProcessTool::addBoxToolItemSLOT(QToolAbstract* item)
{
    QVector<QString> xnodepath = item->getToolXpath();
    QString toolName = item->getToolName();

    QTreeWidgetItem* parentItem = findOrCreateParentItem(xnodepath);

    // 检查该父项是否已经绑定了 toolButton
    if (parentItem && ui.treeWidgetToolBox->itemWidget(parentItem, 0) == nullptr) {
        QTreeWidgetItem* actionItem = new QTreeWidgetItem(parentItem);
        parentItem->addChild(actionItem);
        QPushButton* button = new QPushButton(ui.treeWidgetToolBox);
        button->setText(toolName);
        ui.treeWidgetToolBox->setItemWidget(actionItem, 0, button);
        connect(button, SIGNAL(clicked()), item, SLOT(excute()));
        item->setParent(ui.treeWidgetToolBox);
        qDebug() << "ToolButton bound to parent:" << actionItem->text(0);
    }
    else {
        qDebug() << "ToolButton already bound to parent:" << parentItem->text(0);
    }

}


// 根据路径查找或创建父项
QTreeWidgetItem* RasterProcessTool::findOrCreateParentItem( QVector<QString>& path) {
    QTreeWidgetItem* currentItem = nullptr;

    // 从树的顶层开始查找
    for ( QString& nodeName : path) {
        if (currentItem == nullptr) {
            // 如果是顶级节点
            currentItem = findOrCreateTopLevelItem(nodeName);
        }
        else {
            // 如果是子节点，查找当前父项下是否存在该子节点
            currentItem = findChildItemByName(currentItem, nodeName);
            if (currentItem == nullptr) {
                currentItem = new QTreeWidgetItem(currentItem);
                currentItem->setText(0, nodeName);
            }
        }
    }

    return currentItem;
}

// 查找顶级节点，如果没有找到则创建
QTreeWidgetItem* RasterProcessTool::findOrCreateTopLevelItem( QString& name) {
    for (int i = 0; i < ui.treeWidgetToolBox->topLevelItemCount(); ++i) {
        QTreeWidgetItem* item = ui.treeWidgetToolBox->topLevelItem(i);
        if (item->text(0) == name) {
            return item;
        }
    }

    // 如果没有找到，创建新的顶级节点
    QTreeWidgetItem* newItem = new QTreeWidgetItem(ui.treeWidgetToolBox);
    newItem->setText(0, name);
    return newItem;
}

// 查找子节点，如果没有找到则返回 nullptr
QTreeWidgetItem* RasterProcessTool::findChildItemByName(QTreeWidgetItem* parentItem,  QString& name) {
    for (int i = 0; i < parentItem->childCount(); ++i) {
        QTreeWidgetItem* childItem = parentItem->child(i);
        if (childItem->text(0) == name) {
            return childItem;
        }
    }
    return nullptr;
}







