#include "MainWindow.h"
#include <QTableView>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QDebug>
#include <QHeaderView>
#include "SpellsTableModel.h"
#include "SpellViewer.h"
#include "SpellFilterViewer.h"

MainWindow::MainWindow(Spells spells, QWidget *parent)
    : QMainWindow(parent)
{
    setupUi(spells);
}

MainWindow::~MainWindow()
{}

void MainWindow::setupUi(Spells &spells)
{
    QWidget *widget = new QWidget(this);
    QHBoxLayout *layout = new QHBoxLayout();

    QVBoxLayout *rightLayout = new QVBoxLayout();

    _table = new QTableView(this);
    _model = new SpellsTableModel(spells, _table);
    _table->setModel(_model);
    _table->resizeColumnsToContents();
    _table->resizeRowsToContents();
    _table->setSortingEnabled(true);
    _table->sortByColumn(0, Qt::AscendingOrder);
    _table->setSelectionBehavior(QAbstractItemView::SelectRows);
    _table->setSelectionMode(QAbstractItemView::SingleSelection);
    rightLayout->addWidget(_table);

    _spellViewer = new SpellViewer(this);
    rightLayout->addWidget(_spellViewer);

    _filterViewer = new SpellFilterViewer(this);
    _filterViewer->populate(spells);
    _filterViewer->setResults(_model->rowCount());
    _filterViewer->setMinimumWidth(400);
    _filterViewer->setMaximumWidth(400);
    layout->addWidget(_filterViewer, 1);

    layout->addLayout(rightLayout, 2);
    widget->setLayout(layout);
    this->setCentralWidget(widget);

    connect(_table->selectionModel(), &QItemSelectionModel::selectionChanged, this, &MainWindow::onSelectedSpellChanged);
    connect(_filterViewer, &SpellFilterViewer::filterChanged, this, &MainWindow::onSpellFilterChanged);
    connect(_model, &SpellsTableModel::layoutChanged, this, &MainWindow::onModelLayoutChanged);

    _table->selectRow(0);
}

void MainWindow::onSelectedSpellChanged(const QItemSelection &selected, const QItemSelection&)
{
    _spellViewer->setSpell(_model->spell(selected.indexes().at(0).row()));
}

void MainWindow::onModelLayoutChanged()
{
    if(_model->rowOf(_spellViewer->spell()) != -1)
    {
        _table->selectRow(_model->rowOf(_spellViewer->spell()));
    }
    else
    {
        _table->selectRow(0);
        _spellViewer->setSpell(_model->spell(0));
    }
}

void MainWindow::onSpellFilterChanged()
{
    SpellFilter *filter = _filterViewer->toFilter();
    _model->setSpellFilter(_filterViewer->toFilter());
    delete filter;
    _table->resizeRowsToContents();
    _table->sortByColumn(_table->horizontalHeader()->sortIndicatorSection(), _table->horizontalHeader()->sortIndicatorOrder());
    _filterViewer->setResults(_model->rowCount());
}
