#include "markedfiles.h"
#include <QVBoxLayout>
#include <QTableView>
#include <QSqlTableModel>
#include <QPushButton>
#include <QHeaderView>
#include <QSqlQuery>

MarkedFiles::MarkedFiles(QWidget *parent) : QDialog(parent)
{
    setWindowTitle(tr("Marked files"));

    QVBoxLayout *layout = new QVBoxLayout(this);
    m_tableView = new QTableView(this);
    m_tableView->verticalHeader()->setDefaultSectionSize(1);

    QSqlDatabase db = QSqlDatabase::database();
    m_model = new QSqlTableModel(this, db);

    m_model->setTable("files");
    m_model->removeColumn(0);
    m_model->setHeaderData(0, Qt::Horizontal, tr("Filename"));
    m_model->select();

    m_tableView->setModel(m_model);
    m_tableView->resizeColumnsToContents();
    m_tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);

    QHBoxLayout *hlayout = new QHBoxLayout;
    QPushButton *clearSelectedButton = new QPushButton(tr("Clear selected"), this);
    QPushButton *clearAllButton = new QPushButton(tr("Clear all"), this);

    connect(clearSelectedButton, &QPushButton::pressed, this, &MarkedFiles::clearSelected);
    connect(clearAllButton, &QPushButton::pressed, this, &MarkedFiles::clearAll);

    layout->addWidget(m_tableView);
    layout->addLayout(hlayout);
    hlayout->addWidget(clearSelectedButton);
    hlayout->addWidget(clearAllButton);

    resize(800, 600);
}

void MarkedFiles::clearSelected()
{

    QSqlDatabase db = QSqlDatabase::database();
    QSqlQuery query("DELETE FROM files where file = ?", db);
    QModelIndexList rows = m_tableView->selectionModel()->selectedRows();
    QStringList files;
    for(const QModelIndex &row : rows)
    {
        files.append(row.data().toString());
    }
    query.bindValue(0, files);
    query.execBatch();
    m_model->select();
}

void MarkedFiles::clearAll()
{
    QSqlDatabase db = QSqlDatabase::database();
    QSqlQuery("DELETE FROM files", db);
    m_model->select();
}
