#include "gui/widgets/poster.h"
#include "core/anime_db.h"
#include "core/session.h"
#include <QFrame>
#include <QMessageBox>
#include <QLabel>
#include <QHBoxLayout>
#include <QByteArray>
#include <QPixmap>
#include <curl/curl.h>

static size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userdata) {
	reinterpret_cast<QByteArray*>(userdata)->append(reinterpret_cast<char*>(contents), size * nmemb);
	return size * nmemb;
}

static QByteArray SendRequest(std::string url) {
	QByteArray userdata;
	CURL* curl = curl_easy_init();
	if (curl) {
		curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, &userdata);
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &WriteCallback);
		/* Use system certs... useful on Windows. */
		curl_easy_setopt(curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NATIVE_CA);
		CURLcode res = curl_easy_perform(curl);
		session.IncrementRequests();
		curl_easy_cleanup(curl);
		if (res != CURLE_OK) {
			QMessageBox box(QMessageBox::Icon::Critical, "",
			                QString("curl_easy_perform(curl) failed!: ") + QString(curl_easy_strerror(res)));
			box.exec();
		}
	}
	return userdata;
}

Poster::Poster(int id, QWidget* parent) : QFrame(parent) {
	QHBoxLayout* layout = new QHBoxLayout(this);
	layout->setContentsMargins(1, 1, 1, 1);

	setFixedSize(150, 225);
	setFrameShape(QFrame::Box);
	setFrameShadow(QFrame::Plain);
	
	const Anime::Anime& anime = Anime::db.items[id];
	QByteArray ret = SendRequest(anime.GetPosterUrl());

	img.loadFromData(ret);
	QPixmap pixmap = QPixmap::fromImage(img);

	label = new QLabel(this);
	label->setAlignment(Qt::AlignCenter);
	layout->addWidget(label);
}

void Poster::resizeEvent(QResizeEvent* event) {
	QPixmap pixmap = QPixmap::fromImage(img);
	label->setPixmap(pixmap.scaled(label->width(), label->height(), Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation));
}

#include "gui/widgets/moc_poster.cpp"
