#include "gui/window.h"
#include "core/config.h"
#include "core/session.h"
#include "services/services.h"
#include "gui/dialog/settings.h"
#include "gui/pages/anime_list.h"
#include "gui/pages/now_playing.h"
#include "gui/pages/statistics.h"
#include "gui/sidebar.h"
#include "gui/ui_utils.h"
#include <QApplication>
#include <QFile>
#include <QMainWindow>
#include <QMenuBar>
#include <QPlainTextEdit>
#include <QStackedWidget>
#include <QTextStream>
#if MACOSX
#include "sys/osx/dark_theme.h"
#elif WIN32
#include "sys/win32/dark_theme.h"
#endif

/* note that this code was originally created for use in
   wxWidgets, but I thought the API was a little meh, so
   I switched to Qt. */

enum class Pages {
	NOW_PLAYING,

	ANIME_LIST,
	HISTORY,
	STATISTICS,

	SEARCH,
	SEASONS,
	TORRENTS
};

MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) {
	main_widget = new QWidget(parent);

	SideBar* sidebar = new SideBar(main_widget);
	sidebar->AddItem("Now Playing", SideBar::CreateIcon(":/icons/16x16/film.png"));
	sidebar->AddSeparator();
	sidebar->AddItem("Anime List", SideBar::CreateIcon(":/icons/16x16/document-list.png"));
	sidebar->AddItem("History", SideBar::CreateIcon(":/icons/16x16/clock-history-frame.png"));
	sidebar->AddItem("Statistics", SideBar::CreateIcon(":/icons/16x16/chart.png"));
	sidebar->AddSeparator();
	sidebar->AddItem("Search", SideBar::CreateIcon(":/icons/16x16/magnifier.png"));
	sidebar->AddItem("Seasons", SideBar::CreateIcon(":/icons/16x16/calendar.png"));
	sidebar->AddItem("Torrents", SideBar::CreateIcon(":/icons/16x16/feed.png"));
	sidebar->setFixedWidth(128);
	sidebar->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);

	QStackedWidget* stack = new QStackedWidget(main_widget);
	stack->addWidget(new NowPlayingWidget(main_widget));
	stack->addWidget(new AnimeListWidget(main_widget));
	stack->addWidget(new StatisticsWidget(main_widget));

	connect(sidebar, &SideBar::CurrentItemChanged, stack, [stack](int index) {
		switch (index) {
			case 0:
			case 1: stack->setCurrentIndex(index); break;
			case 3: stack->setCurrentIndex(2); break;
			default: break;
		}
	});
	sidebar->setCurrentRow(2);

	/* Menu Bar */
	QAction* action;
	QMenuBar* menubar = new QMenuBar(parent);
	QMenu* menu = menubar->addMenu("&File");
	QMenu* submenu = menu->addMenu("&Library folders");
	action = submenu->addAction("&Add new folder...");
	action = menu->addAction("&Scan available episodes");

	menu->addSeparator();

	action = menu->addAction("Play &next episode");
	action = menu->addAction("Play &random episode");
	menu->addSeparator();
	action = menu->addAction("E&xit", qApp, &QApplication::quit);

	menu = menubar->addMenu("&Services");
	action = menu->addAction("Synchronize &list", [this, stack] {
		Services::Synchronize();
		((AnimeListWidget*)stack->widget((int)Pages::ANIME_LIST))->RefreshList();
	});

	menu->addSeparator();

	submenu = menu->addMenu("&AniList");
	action = submenu->addAction("Go to my &profile");
	action = submenu->addAction("Go to my &stats");

	submenu = menu->addMenu("&Kitsu");
	action = submenu->addAction("Go to my &feed");
	action = submenu->addAction("Go to my &library");
	action = submenu->addAction("Go to my &profile");

	submenu = menu->addMenu("&MyAnimeList");
	action = submenu->addAction("Go to my p&anel");
	action = submenu->addAction("Go to my &profile");
	action = submenu->addAction("Go to my &history");

	menu = menubar->addMenu("&Tools");
	submenu = menu->addMenu("&Export anime list");
	action = submenu->addAction("Export as &Markdown...");
	action = submenu->addAction("Export as MyAnimeList &XML...");

	menu->addSeparator();

	action = menu->addAction("Enable anime &recognition");
	action->setCheckable(true);
	action = menu->addAction("Enable auto &sharing");
	action->setCheckable(true);
	action = menu->addAction("Enable &auto synchronization");
	action->setCheckable(true);

	menu->addSeparator();

	action = menu->addAction("&Settings", [this] {
		SettingsDialog dialog(this);
		dialog.exec();
	});

	setMenuBar(menubar);

	QHBoxLayout* layout = new QHBoxLayout(main_widget);
	layout->addWidget(sidebar, 0, Qt::AlignLeft | Qt::AlignTop);
	layout->addWidget(stack);
	setCentralWidget(main_widget);

	ThemeChanged();
}

void MainWindow::SetStyleSheet(enum Themes theme) {
	switch (theme) {
		case Themes::DARK: {
			QFile f(":qdarkstyle/dark/darkstyle.qss");
			if (!f.exists())
				return; // fail
			f.open(QFile::ReadOnly | QFile::Text);
			QTextStream ts(&f);
			setStyleSheet(ts.readAll());
			break;
		}
		default: setStyleSheet(""); break;
	}
}

void MainWindow::ThemeChanged() {
	switch (session.config.theme) {
		case Themes::LIGHT: {
#if MACOSX
			if (osx::DarkThemeAvailable())
				osx::SetToLightTheme();
			else
#else
			SetStyleSheet(Themes::LIGHT);
#endif
				break;
		}
		case Themes::DARK: {
#if MACOSX
			if (osx::DarkThemeAvailable())
				osx::SetToDarkTheme();
			else
#else
			SetStyleSheet(Themes::DARK);
#endif
				break;
		}
		case Themes::OS: {
#if MACOSX
			if (osx::DarkThemeAvailable())
				osx::SetToAutoTheme();
			else
#elif defined(WIN32)
			if (win32::DarkThemeAvailable()) {
				if (win32::IsInDarkTheme()) {
					SetStyleSheet(Themes::DARK);
				} else {
					SetStyleSheet(Themes::LIGHT);
				}
			} else
#endif
				/* Currently OS detection only supports Windows and macOS.
				   Please don't be shy if you're willing to port it to other OSes
				   (or desktop environments, or window managers) */
				SetStyleSheet(Themes::LIGHT);
			break;
		}
	}
}

void MainWindow::SetActivePage(QWidget* page) {
	this->setCentralWidget(page);
}

void MainWindow::closeEvent(QCloseEvent* event) {
	session.config.Save();
	event->accept();
}

#include "gui/moc_window.cpp"
