#include "gui/widgets/anime_info.h"
#include "core/anime.h"
#include "core/anime_db.h"
#include "core/strings.h"
#include "gui/translate/anime.h"
#include "gui/widgets/text.h"
#include "services/services.h"
#include <QHBoxLayout>
#include <QTextStream>

AnimeInfoWidgetGetMetadataThread::AnimeInfoWidgetGetMetadataThread(QObject *parent) : QThread(parent)
{
}

void AnimeInfoWidgetGetMetadataThread::AddToQueue(int id)
{
	const std::lock_guard<std::mutex> guard(queue_mutex_);
	queue_.push(id);
}

/* processes the queue... */
void AnimeInfoWidgetGetMetadataThread::run()
{
	queue_mutex_.lock();
	while (!queue_.empty() && !isInterruptionRequested()) {
		int id = queue_.front();

		queue_mutex_.unlock();

		if (Services::RetrieveAnimeMetadata(id))
			emit NeedRefresh(id);

		queue_mutex_.lock();

		queue_.pop();
	}
	queue_mutex_.unlock();
}

/* all widgets share this thread */
static AnimeInfoWidgetGetMetadataThread get_metadata_thread;

AnimeInfoWidget::AnimeInfoWidget(QWidget *parent) : QWidget(parent)
{
	QVBoxLayout *layout = new QVBoxLayout(this);

	_title.GetHeader().SetText(Strings::Translate("Alternative titles"));
	layout->addWidget(&_title);

	_details.GetHeader().SetText(Strings::Translate("Details"));

	const std::vector<std::pair<std::string, std::string>> items = {
	    {Strings::Translate("Type:"),      ""},
        {Strings::Translate("Episodes:"),  ""},
	    {Strings::Translate("Status:"),    ""},
        {Strings::Translate("Season:"),    ""},
	    {Strings::Translate("Genres:"),    ""},
        {Strings::Translate("Producers:"), ""},
	    {Strings::Translate("Score:"),     ""},
	};

	_details.GetContent().SetData(items);

	layout->addWidget(&_details);

	_synopsis.GetHeader().SetText(Strings::Translate("Synopsis"));
	layout->addWidget(&_synopsis);

	layout->addStretch();

	/* ... */
	connect(&get_metadata_thread, &AnimeInfoWidgetGetMetadataThread::NeedRefresh, this, [this](int id) {
		setUpdatesEnabled(false);

		if (id == id_)
			RefreshGenres(Anime::db.items[id]);

		setUpdatesEnabled(true);
	});
}

AnimeInfoWidget::AnimeInfoWidget(const Anime::Anime &anime, QWidget *parent) : AnimeInfoWidget(parent)
{
	SetAnime(anime);
}

void AnimeInfoWidget::SetAnime(const Anime::Anime &anime)
{
	setUpdatesEnabled(false);

	id_ = anime.GetId();

	get_metadata_thread.AddToQueue(id_);
	if (!get_metadata_thread.isRunning())
		get_metadata_thread.start();

	/* alt titles */
	_title.GetContent().SetText(Strings::Implode(anime.GetTitleSynonyms(), ", "));

	RefreshGenres(anime);

	_synopsis.GetContent().SetText(anime.GetSynopsis());

	setUpdatesEnabled(true);

	updateGeometry();
}

void AnimeInfoWidget::RefreshGenres(const Anime::Anime &anime)
{
	/* we have to convert ALL of these strings to
	 * QString because QTextStream sucks and assumes
	 * Latin-1 (on Windows?) */
	const auto genres = anime.GetGenres();
	const auto producers = anime.GetProducers();

	const std::vector<std::pair<std::string, std::string>> items = {
	    {Strings::Translate("Type:"), Translate::ToLocalString(anime.GetFormat())},
	    {Strings::Translate("Episodes:"), Strings::ToUtf8String(anime.GetEpisodes())},
	    {Strings::Translate("Status:"), Translate::ToLocalString(anime.GetAiringStatus())},
	    {Strings::Translate("Season:"), Translate::ToLocalString(anime.GetSeason())},
	    {Strings::Translate("Genres:"), (genres.size() > 1) ? Strings::Implode(genres, ", ") : "-"},
	    {Strings::Translate("Producers:"), (producers.size() > 1) ? Strings::Implode(producers, ", ") : "-"},
	    {Strings::Translate("Score:"), Strings::ToUtf8String(anime.GetAudienceScore()) + "%"},
	};

	_details.GetContent().SetData(items);
}
