#ifndef __anime_list_h
#define __anime_list_h
#include <vector>
#include <QStyledItemDelegate>
#include <QSortFilterProxyModel>
#include <QAbstractListModel>
#include <QTreeView>
#include <QWidget>
#include "anime.h"
#include "progress.h"

class AnimeListWidgetDelegate : public QStyledItemDelegate {
    Q_OBJECT

	public:
		explicit AnimeListWidgetDelegate(QObject *parent);

		QWidget *createEditor(QWidget *, const QStyleOptionViewItem &, const QModelIndex &) const override;
		void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override;

	protected:
		AnimeProgressBar progress_bar;
};

class AnimeListWidgetSortFilter : public QSortFilterProxyModel
{
    Q_OBJECT

	public:
		AnimeListWidgetSortFilter(QObject *parent = nullptr);

	protected:
		bool lessThan(const QModelIndex &l, const QModelIndex &r) const override;
};

class AnimeListWidgetModel : public QAbstractListModel {
	Q_OBJECT

	public:
		enum columns {
			AL_TITLE,
			AL_PROGRESS,
			AL_EPISODES,
			AL_SCORE,
			AL_AVG_SCORE,
			AL_TYPE,
			AL_SEASON,
			AL_STARTED,
			AL_COMPLETED,
			AL_UPDATED,
			AL_NOTES,
			
			NB_COLUMNS
		};

		AnimeListWidgetModel(QWidget* parent, AnimeList* alist);
		~AnimeListWidgetModel() override = default;
		int rowCount(const QModelIndex& parent = QModelIndex()) const override;
		int columnCount(const QModelIndex& parent = QModelIndex()) const override;
		QVariant data(const QModelIndex& index, int role) const override;
		QVariant headerData(const int section, const Qt::Orientation orientation, const int role) const override;
		Anime* GetAnimeFromIndex(const QModelIndex& index);
		void UpdateAnime(Anime& anime);
		void Update(const AnimeList& new_list);

	private:
		//void AddAnime(AnimeList& list);
		AnimeList& list;
};

/* todo: rename these to "page" or something more
   sensible than "widget" */
class AnimeListWidget : public QWidget {
	Q_OBJECT

	public:
		AnimeListWidget(QWidget* parent);
		void SyncAnimeList();
		void FreeAnimeList();
		int GetTotalAnimeAmount();
		int GetTotalEpisodeAmount();
		int GetTotalWatchedAmount();
		int GetTotalPlannedAmount();
		double GetAverageScore();
		double GetScoreDeviation();

	protected:
		void paintEvent(QPaintEvent*) override;
		void InitStyle(QStyleOptionTabWidgetFrame *option) const;
		void InitBasicStyle(QStyleOptionTabWidgetFrame *option) const;
		void SetupLayout();
		void showEvent(QShowEvent*) override;
		void resizeEvent(QResizeEvent* e) override;

	private slots:
		void DisplayColumnHeaderMenu();
		void DisplayListMenu();
		void ItemDoubleClicked();
		void SetColumnDefaults();
		int VisibleColumnsCount() const;

	private:
		QTabBar* tab_bar;
		QTreeView* tree_view;
		QRect panelRect;
		std::vector<AnimeListWidgetSortFilter*> sort_models;
		std::vector<AnimeList> anime_lists;
};
#endif // __anime_list_h