#include "AronTreeWidgetDictInputModalController.h"

#include <RobotAPI/libraries/aron/core/type/variant/All.h>

#include "../../visitors/AronTreeWidgetCreator.h"

namespace armarx
{
    AronTreeWidgetDictInputModalController::AronTreeWidgetDictInputModalController(const std::string& label, AronTreeWidgetItem* item, QTreeWidget* parent) :
        AronTreeWidgetModal(label, item, parent)
    {
        widget.setupUi(this);

        // set header
        widget.groupBoxInput->setTitle(QString::fromStdString(label));
        reset();

        // connect signals
        connect(widget.pushButtonAddElement, &QPushButton::clicked,
                this, &AronTreeWidgetDictInputModalController::addEmptyElement);

        connect(widget.pushButtonReset, &QPushButton::clicked,
                  this, &AronTreeWidgetDictInputModalController::reset);
        connect(widget.pushButtonSubmit, &QPushButton::clicked,
                  this, &AronTreeWidgetDictInputModalController::submit);

    }

    void AronTreeWidgetDictInputModalController::submit()
    {
        for (const auto& added : addedItems)
        {
            //item->addChild(added->copy());
        }

        AronTreeWidgetModal::submit();
    }

    void AronTreeWidgetDictInputModalController::reset()
    {
        AronTreeWidgetModal::reset();

        // reset to initial value
        widget.treeWidgetDict->clear();
        for (int i = 0; i < init.childCount(); ++i)
        {
            auto el = init.child(i);
            widget.treeWidgetDict->addTopLevelItem(el->clone());
        }
    }

    void AronTreeWidgetDictInputModalController::addEmptyElement()
    {
        QString s = widget.lineEditKey->text();
        widget.lineEditKey->setText("Enter Key");

        if (widget.treeWidgetDict->findItems(s, Qt::MatchFlag::MatchExactly, 0).empty())
        {
            auto t = item->aronType;
            auto d = aron::type::Dict::DynamicCastAndCheck(t);
            auto ac = d->getAcceptedType();

            AronTreeWidgetCreatorVisitor v(nullptr);
            v.setTopLevelWidget(widget.treeWidgetDict);
            aron::type::visit(v, ac);

            if (v.createdQWidgetItem)
            {
                v.createdQWidgetItem->setText(aron_tree_widget::constantes::TREE_WIDGET_ITEM_NAME,
                                              s);
                addedItems.push_back(v.createdQWidgetItem);
                widget.treeWidgetDict->addTopLevelItem(v.createdQWidgetItem);
            }
        }
    }
}