#include "SkillGroupBox.h"

#include <QHBoxLayout>
#include <QVBoxLayout>

namespace armarx::skills::gui
{
    void
    SkillGroupBox::handleSearch()
    {
        std::string search = this->searchBar->text().toStdString();
        emit searchRequest(search);
    }

    void
    SkillGroupBox::filterAndFetch()
    {
        memory->updateFromMemory();
        handleSearch();
    }

    void
    SkillGroupBox::connectGui(std::string observerName)
    {
        setTitle(QString::fromStdString(observerName));
    }

    void
    SkillGroupBox::updateGui(SkillManagerWrapper::Snapshot update)
    {
        skillTreeWidget->updateGui(update.skills);
    }

    void
    SkillGroupBox::searchCallback()
    {
        this->skillTreeWidget->updateGui(memory->getSkills());
    }

    void
    SkillGroupBox::setupUi()
    {
        this->setTitle(QString::fromStdString(GROUP_BOX_TITLE));

        this->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);


        // construct widgets
        this->searchBar = new QLineEdit();
        this->acceptSearchButton = new QPushButton();
        this->skillTreeWidget = new SkillTreeWidget(memory, this);

        // layouting
        QHBoxLayout* searchLayout = new QHBoxLayout();
        QVBoxLayout* layout = new QVBoxLayout();
        this->setLayout(layout);
        layout->addLayout(searchLayout);
        layout->addWidget(this->skillTreeWidget);

        searchLayout->addWidget(this->searchBar);
        searchLayout->addWidget(this->acceptSearchButton);

        // text
        this->searchBar->setPlaceholderText(QString::fromStdString("Search ..."));
        this->acceptSearchButton->setText(QString::fromStdString("Update and Search"));

        // some further information to explain the search bar
        this->searchBar->setToolTip(
            QString::fromStdString("Accepting the search (with Enter) searches all currently known "
                                   "skills. This is not the same as 'Update & Search'!"));

        connectSignals();
    }

    void
    SkillGroupBox::connectSignals()
    {
        connect(
            this->acceptSearchButton, &QPushButton::clicked, this, &SkillGroupBox::filterAndFetch);
        connect(this->searchBar, &QLineEdit::editingFinished, this, &SkillGroupBox::handleSearch);
        connect(this,
                &SkillGroupBox::searchRequest,
                this->memory.get(),
                &SkillManagerWrapper::acceptSearchRequest);
        connect(memory.get(),
                &SkillManagerWrapper::searchAccepted,
                this,
                &SkillGroupBox::searchCallback);

        connect(skillTreeWidget,
                &SkillTreeWidget::updateSkillDetails,
                this,
                &SkillGroupBox::updateSkillDetails);

        // disconnect
        connect(
            this, &SkillGroupBox::disconnectGui, skillTreeWidget, &SkillTreeWidget::disconnectGui);
    }
} // namespace armarx::skills::gui