#ifndef DATABASEVIEW_H
#define DATABASEVIEW_H

#include <QDialog>
#include <QWidget>
#include <QSqlQueryModel>
#include <QTableView>
#include <QListWidget>
#include <QComboBox>
#include <QLineEdit>
#include "database.h"

class SelectColumnsDialog : public QDialog
{
    Q_OBJECT
    QListWidget *m_listWidget;
public:
    explicit SelectColumnsDialog(QWidget *parent = nullptr);
    void setColumns(QStringList columns);
    QStringList selectedColumns();
};

class FITSFileModel : public QSqlQueryModel
{
    Q_OBJECT
    QStringList m_columns;
    QString m_sort;
    QStringList m_key;
    QStringList m_value;
    QStringList m_limit;
    QSet<QString> m_markedFiles;
    Database *m_database;
    bool m_loaded = false;
public:
    explicit FITSFileModel(Database *database, QObject *parent = nullptr);
    void sort(int column, Qt::SortOrder order) override;
    void setColumns(const QStringList &columns);
    void setFilter(const QStringList &key, const QStringList &value, const QStringList &limit);
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
    void filesMarked(const QModelIndexList &indexes);
    void filesUnmarked(const QModelIndexList &indexes);
    void load();
protected:
    void prepareQuery();
};

class CopyTableView : public QTableView
{
    Q_OBJECT
public:
    explicit CopyTableView(QWidget *parent = nullptr);
    void keyPressEvent(QKeyEvent *event);
};

class DatabaseTableView : public CopyTableView
{
    Q_OBJECT
public:
    explicit DatabaseTableView(QWidget *parent = nullptr);
protected:
    void contextMenuEvent(QContextMenuEvent *event) override;
signals:
    void filesMarked(QModelIndexList indexes);
    void filesUnmarked(QModelIndexList indexes);
    void openFile(QModelIndexList indexes);
    void openDir(QModelIndexList indexes);
};

class DataBaseView : public QWidget
{
    Q_OBJECT
    Database *m_database;
    DatabaseTableView *m_tableView;
    FITSFileModel *m_model;
    QComboBox *m_filterKeyword[3];
    QLineEdit *m_search[3];
    QLineEdit *m_limit[3];
public:
    explicit DataBaseView(Database *database, QWidget *parent = nullptr);
    ~DataBaseView() override;
public slots:
    void selectColumns();
    void loadDatabase();
    void itemActivated(const QModelIndex &index);
    void applyFilter();
    bool exportCSV(const QString &path);
    void visible(bool visible);
signals:
    void loadFile(QString file);
};

#endif // DATABASEVIEW_H
