#ifndef DATABASETREE_H
#define DATABASETREE_H

#include <QAbstractItemModel>
#include <QComboBox>
#include <QDialog>
#include <QFont>
#include <QSqlQuery>
#include <QSqlQueryModel>
#include <QTableView>
#include <QTreeView>
#include <memory>

class Database;
class TreeNode;

class DatabaseTreeSettings : public QDialog
{
    Q_OBJECT
public:
    explicit DatabaseTreeSettings(const QStringList &data, QStringList keywords, QWidget *parent = nullptr);
    QString keywords() const;
    QString aggregrationFunc() const;
public slots:
    void acceptButton();
private:
    QVector<QComboBox*> _keywordsSelect;
    QComboBox *_aggregateFunction;
};

class DatabaseTree : public QAbstractItemModel
{
public:
    explicit DatabaseTree(Database *database, QObject *parent = nullptr);
    void setKeys(const QStringList &keys);
    QStringList keys() const;
    QModelIndex index(int row, int column, const QModelIndex &parent) const override;
    QModelIndex parent(const QModelIndex &index) const override;
    int rowCount(const QModelIndex &index) const override;
    int columnCount(const QModelIndex &index) const override;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
    bool canFetchMore(const QModelIndex &parent) const override;
    void fetchMore(const QModelIndex &parent) override;
    QVariant headerData(int section, Qt::Orientation orientation, int role) const override;
    void load();
    QSqlQuery getGroupQuery(const QString &aggregateFunc) const;
private:
    void prepareQueries();
    void fillNode(TreeNode *node);
    Database *_database = nullptr;
    std::unique_ptr<TreeNode> _rootNode;
    QVector<QSqlQuery> _queries;
    QStringList _keys;
    QFont _italicFont;
    bool _loaded = false;
};

class DatabaseTreeView : public QWidget
{
    Q_OBJECT
public:
    explicit DatabaseTreeView(Database *database, QWidget *parent = nullptr);
    virtual ~DatabaseTreeView();
public slots:
    void addFilter();
    void removeFilter();
    void filterChanged(int index);
    void visible(bool visible);
private:
    void setQuery(const QString &func);
signals:
    void loadFile(const QString &file);
private:
    QComboBox *_filters = nullptr;
    QTreeView *_treeView = nullptr;
    QTableView *_tableView = nullptr;
    DatabaseTree *_model = nullptr;
    QSqlQueryModel *_sqlModel = nullptr;
    Database *_database = nullptr;
    bool _loaded = false;
};

#endif // DATABASETREE_H
