#pragma once

#include <QWidget>
#include <QTreeWidget>
#include <QMenu>
#include <QAction>
#include "db/dao/categorydao.h"
#include "db/dao/ruledao.h"

class CategoryTreeWidget : public QTreeWidget
{
    Q_OBJECT

public:
    explicit CategoryTreeWidget(QWidget *parent = nullptr);
    
    void setAccountId(qint64 accountId);
    void refresh();
    void addCategory(const Category& cat, QTreeWidgetItem* parent = nullptr);
    QTreeWidgetItem* findItemByCategoryId(qint64 categoryId);
    
signals:
    void categorySelected(const Category& cat);
    void categoryDoubleClicked(const Category& cat);
    void assignCategoryRequested(qint64 mailId, qint64 categoryId);
    void categoryCreated(const Category& cat);
    void categoryEdited(const Category& cat);
    void categoryDeleted(qint64 categoryId);
    void mailCategorized(qint64 mailId, const QVector<qint64>& categoryIds);

public slots:
    void onMailSelected(qint64 mailId);
    void onCategoryContextMenu(const QPoint& pos);

private:
    qint64 m_accountId = -1;
    QMap<qint64, QTreeWidgetItem*> m_categoryItems;
    QMenu* m_contextMenu = nullptr;
    
    void setupContextMenu();
    void onNewCategory();
    void onEditCategory(QTreeWidgetItem* item);
    void onDeleteCategory(QTreeWidgetItem* item);
    void onAssignToSelectedMails(QTreeWidgetItem* item);
    void loadCategories();
    Category itemToCategory(QTreeWidgetItem* item) const;
};