#include "gui/pages/now_playing.h"
#include "core/anime_db.h"
#include "core/strings.h"
#include "gui/widgets/anime_info.h"
#include "gui/widgets/poster.h"
#include "gui/widgets/text.h"

#include <QHBoxLayout>
#include <QLabel>
#include <QStackedWidget>
#include <QVBoxLayout>
#include <QWidget>

#include "anitomy/anitomy.h"

namespace NowPlayingPages {

Default::Default(QWidget* parent) : QWidget(parent) {
	QVBoxLayout* layout = new QVBoxLayout(this);
	layout->setContentsMargins(0, 0, 0, 0);

	title_.SetText(Strings::Translate("Now Playing"));
	layout->addWidget(&title_);

	layout->addStretch();
}

Playing::Playing(QWidget* parent) : QWidget(parent) {
	QHBoxLayout* layout = new QHBoxLayout(this);

	_main.setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);

	QVBoxLayout* main_layout = new QVBoxLayout(&_main);
	main_layout->setContentsMargins(0, 0, 0, 0);

	main_layout->addWidget(&_title);

	_info.setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
	_info.layout()->setContentsMargins(0, 0, 0, 0);
	main_layout->addWidget(&_info);

	/* "sidebar", includes... just the anime image :) */
	QVBoxLayout* sidebar_layout = new QVBoxLayout(&_sidebar);
	sidebar_layout->setContentsMargins(0, 0, 0, 0);

	sidebar_layout->addWidget(&_poster);

	sidebar_layout->addStretch();

	layout->addWidget(&_sidebar);
	layout->addWidget(&_main);
	layout->setSpacing(10);
	layout->setContentsMargins(0, 0, 0, 0);
}

int Playing::GetPlayingAnime() {
	return _id;
}

void Playing::SetPlayingAnime(const Anime::Anime& anime, const anitomy::Elements& info) {
	if (_id == anime.GetId()
		&& _episode == Strings::ToInt(Strings::ToUtf8String(info.get(anitomy::kElementEpisodeNumber))))
		return;
	_id = anime.GetId();
	_episode = Strings::ToInt(Strings::ToUtf8String(info.get(anitomy::kElementEpisodeNumber)));
	_title.SetText(anime.GetUserPreferredTitle());
	_info.SetAnime(anime);
	_poster.SetAnime(anime);

	updateGeometry();
}

} // namespace NowPlayingPages

NowPlayingPage::NowPlayingPage(QWidget* parent) : QFrame(parent) {
	setBackgroundRole(QPalette::Base);
	QVBoxLayout* layout = new QVBoxLayout(this);

	setFrameShape(QFrame::Box);
	setFrameShadow(QFrame::Sunken);
	setAutoFillBackground(true);

	stack_.addWidget(&default_);
	stack_.addWidget(&playing_);
	layout->addWidget(&stack_);

	SetDefault();
}

void NowPlayingPage::SetDefault() {
	stack_.setCurrentIndex(static_cast<int>(Subpages::Default));
}

int NowPlayingPage::GetPlayingId() {
	return playing_.GetPlayingAnime();
}

void NowPlayingPage::SetPlaying(const Anime::Anime& anime, const anitomy::Elements& info) {
	playing_.SetPlayingAnime(anime, info);
	stack_.setCurrentIndex(static_cast<int>(Subpages::Playing));
	updateGeometry();
}
