#include "breadcrumbview.h"
using namespace Xybrid::UI;

#include <QDebug>
#include <QHeaderView>

BreadcrumbView::BreadcrumbView(QWidget* parent) : QTableView (parent) {
    mdl = new BreadcrumbModel(this);
    setModel(mdl);

    horizontalHeader()->setVisible(false);
    verticalHeader()->setVisible(false);
    horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);

    connect(selectionModel(), &QItemSelectionModel::currentColumnChanged, this, [this](const QModelIndex& index, const QModelIndex&) {
        //qDebug() << "breadcrumb change" << index;
        size_t idx = static_cast<size_t>(index.column());
        if (mdl->actions.size() <= idx) return;
        mdl->actions[idx]->trigger();
        if (shrinkOnSelect) mdl->actions.resize(idx+1);
        emit mdl->layoutChanged();
    });
}

void BreadcrumbView::up() {
    auto ind = currentIndex();
    if (ind.column() > 0) setCurrentIndex(ind.siblingAtColumn(ind.column() - 1));
}

void BreadcrumbView::clear() {
    mdl->actions.clear();
    emit mdl->layoutChanged();
    this->setCurrentIndex(mdl->index(-1, -1));
}

void BreadcrumbView::push(const QString& text, QObject* bind, std::function<void ()> action) {
    mdl->actions.resize(std::min(mdl->actions.size(), static_cast<size_t>(currentIndex().column()) + 1));
    mdl->actions.push_back(std::make_unique<QAction>(text, bind));
    emit mdl->layoutChanged();
    connect(mdl->actions.back().get(), &QAction::triggered, bind, action);
    this->setCurrentIndex(mdl->index(0, static_cast<int>(mdl->actions.size()) - 1));
}

BreadcrumbModel::BreadcrumbModel(QWidget* parent) : QAbstractTableModel(parent) {
    //actions.push_back(std::make_unique<QAction>("Root Graph", this));
}

int BreadcrumbModel::rowCount(const QModelIndex&) const {
    return 1;
}

int BreadcrumbModel::columnCount(const QModelIndex&) const {
    return static_cast<int>(actions.size());
}

QVariant BreadcrumbModel::data(const QModelIndex& index, int role) const {
    if (actions.size() <= static_cast<size_t>(index.column())) return QVariant(); // safety
    if (role == Qt::DisplayRole) {
        return actions[static_cast<size_t>(index.column())]->text();
    }
    if (role == Qt::TextAlignmentRole) return Qt::AlignHCenter + Qt::AlignVCenter;
    return QVariant();
}
