#include "fragmentsorderpresent.h"
#include "DocsManager.h"
#include "command_list.h"
#include "manager_docs.h"
#include <QVBoxLayout>
#include <StoryUnitDocumentParser.h>
#include <comdef.h>

using namespace Components;
using namespace Parse;
using namespace DataModel;

FragmentsOrderPresent::FragmentsOrderPresent(Schedule::CommandsDispatcher *core, FragmentsOrderviewModel *backend, QWidget *parent)
    : QWidget(parent), core_ins(core), table_view(new QTableView(this)) {
    this->table_view->setModel(backend->tableModel());

    auto layout = new QVBoxLayout(this);
    layout->addWidget(table_view);
    connect(this->table_view, &QTableView::doubleClicked, this, &FragmentsOrderPresent::double_click);
}

using namespace CommandList;
void FragmentsOrderPresent::double_click(const QModelIndex &index) {
    if(!index.isValid())
        return;

    QList<QString> path;
    path << index.sibling(index.row(), 0).data().toString();
    path << index.sibling(index.row(), 1).data().toString();

    core_ins->postCommand(StoryboardJumpTo(path));
}

QString FragmentsOrderPresent::name() const { return NAME(FragmentsOrderPresent); }

QWidget *FragmentsOrderPresent::widget() const { return (QWidget *)this; }

FragmentsOrderviewModel::FragmentsOrderviewModel(Core::AppCore *core)
    : core_ins(core), table_base(new QStandardItemModel) {

    table_base->setHorizontalHeaderLabels(QStringList() << "情节名称"
                                                        << "单元名称"
                                                        << "索引值");
}

void FragmentsOrderviewModel::refreshTable() {
    table_base->clear();
    table_base->setHorizontalHeaderLabels(QStringList() << "情节名称"
                                                        << "单元名称"
                                                        << "索引值");

    auto node_list = core_ins->parseCore()->queryOrdersFragment();

    for (auto &ins : node_list) {
        QList<QStandardItem *> row;
        row << new QStandardItem(ins.first->name()[0]);
        row << new QStandardItem(ins.first->name()[1]);
        row << new QStandardItem(QString("%1").arg(ins.second, 8, 'f'));

        for (auto &i : row)
            i->setEditable(false);

        table_base->appendRow(row);
    }
}

QStandardItemModel *FragmentsOrderviewModel::tableModel() const {
    return table_base;
}

QString FragmentsOrderviewModel::name() const {
    return NAME(FragmentsOrderviewModel);
}
