//
// Created by HW on 2023/07/26.
//

// You may need to build the project (run Qt uic code generator) to get "ui_NavBar.h" resolved

#include "navbar.h"
#include "ui_NavBar.h"
#include "config.h"
#include <QTimer>
#include <QtSvg/QtSvg>
#ifdef _DEBUG
#pragma comment(lib, "Qt5Svgd.lib")
#else
#pragma comment(lib, "QtSvg.lib")
#endif
NavBar::NavBar(ConfigResponse *configResponse,QWidget *parent) :
        QWidget(parent), ui(new Ui::NavBar) {
    ui->setupUi(this);
	if (configResponse->succeed) {
		getLogoFromInternet(configResponse);
	}
	else {
		getLogoFromLocal();
	};
	int n = buttonStructs.length();
	int x = (width() - height()*n) / 2;
	for (auto buttonStruct : buttonStructs) {
		MyButton *myButton = new MyButton(buttonStruct, height(), height(), &buttons);
		myButton->setGeometry(x, 0, height(), height());
		x += height();
		buttons << myButton;
	}
	this->setLayout(nullptr);
}

NavBar::~NavBar() {
	for (auto buttonStruct : buttonStructs) {
		delete buttonStruct.image;
		delete buttonStruct.image_cover;
	}
	for(auto button : buttons){
        delete button;
    }
    delete ui;
}

void NavBar::paintEvent(QPaintEvent *event) {
    QWidget::paintEvent(event);

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    QRectF rect(0, 0, this->width(), this->height());
    painter.fillRect(rect, qColor);

	QRectF rect2(0, 0, this->width()/5, this->height());
	painter.drawImage(rect2, *logo);

}
void NavBar::resizeEvent(QResizeEvent *event) {
    QWidget::resizeEvent(event);
	int n = buttonStructs.length();
	int x = (width() - height()*n) / 2;
    for(auto button:buttons){
        button->setSize(event->size().height(),event->size().height(),event->size().height(),event->size().height());
		button->setGeometry(x, 0, event->size().height(), event->size().height());
		x += event->size().height();
        button->update();
    }
}
void NavBar::getLogoFromInternet(ConfigResponse *configResponse) {
	qColor.setNamedColor(configResponse->basic.backgroud_color);
	QUrl url_logo(QString(BASE_URL) + configResponse->basic.logo_url);
	QNetworkRequest *request_logo = new QNetworkRequest(url_logo);
	manager = new QNetworkAccessManager;
	reply = manager->get(*request_logo);
	QTimer timer;
	timer.setInterval(5000);
	connect(reply, &QNetworkReply::finished, &eventLoop,&QEventLoop::quit);
	connect(&timer, &QTimer::timeout,this, &NavBar::cancelDownload);
	timer.stop();
	delete request_logo;
	if (downloadSuccess == true) {
		*buffer = reply->readAll();
		QSvgRenderer *render_logo = new QSvgRenderer(*buffer);
		logo = new QImage(200, 200, QImage::Format_ARGB32);
		QPainter painter_logo(logo);
		render_logo->render(&painter_logo);
		buffer->clear();
		for (auto button : *configResponse->menus) {
			QUrl url_image(QString(BASE_URL) + button.img);
			QNetworkRequest *request_image = new QNetworkRequest(url_image);
			reply = manager->get(*request_image);
			QTimer timer;
			timer.setInterval(5000);
			connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
			connect(&timer, &QTimer::timeout, this, &NavBar::cancelDownload);
			if (!downloadSuccess) {
				break;
			}
			*buffer = reply->readAll();
			QSvgRenderer *render_image = new QSvgRenderer(*buffer);
			QImage *image = new QImage(200, 200, QImage::Format_ARGB32);
			QPainter painter_image(image);
			render_image->render(&painter_image);

			QUrl url_image_cover(QString(BASE_URL) + button.img_cover);
			QNetworkRequest *request_image_cover = new QNetworkRequest(url_image_cover);
			reply = manager->get(*request_image_cover);
			timer.setInterval(5000);
			connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
			connect(&timer, &QTimer::timeout, this, &NavBar::cancelDownload);
			if (!downloadSuccess) {
				break;
			}
			*buffer = reply->readAll();
			QSvgRenderer *render_image_cover = new QSvgRenderer(*buffer);
			QImage *image_cover = new QImage(200, 200, QImage::Format_ARGB32);
			QPainter painter_image_cover(image_cover);
			render_image_cover->render(&painter_image_cover);
			ButtonStruct buttonStruct;
			buttonStruct.image = image;
			buttonStruct.image_cover = image_cover;
			buttonStruct.text = button.title;
			buttonStruct.url = button.url;
			buttonStructs << buttonStruct;
			delete request_image;
			delete render_image;
			delete request_image_cover;
			delete render_image_cover;
		}
	}
	delete manager;
	manager = nullptr;
	
}
void NavBar::storeToBuffer() {
	buffer = new QByteArray;
	
}
void NavBar::cancelDownload() {
	disconnect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
	eventLoop.quit();
	reply->abort();
	downloadSuccess = false;
}

void NavBar::getLogoFromLocal() {
	QString dir = QApplication::applicationDirPath();
	QFile file(dir + DEFAULT_FILE);
	if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
		QMessageBox::warning(nullptr, QString::fromLocal8Bit("错误"), QString::fromLocal8Bit("无法打开配置文件"));
		exit(1);
	}
	buffer->clear();
	*buffer = file.readAll();
	file.close();
	QJsonDocument *qJsonDocument = new QJsonDocument;
	*qJsonDocument = QJsonDocument::fromJson(*buffer);
	QJsonObject *obj_root = new QJsonObject;
	if (qJsonDocument->isObject()) {
		*obj_root = qJsonDocument->object();
		delete qJsonDocument;
		QString logo_path = obj_root->value("basic").toObject().value("logo").toString();
		logo = new QImage(logo_path);
		QString color= obj_root->value("basic").toObject().value("backgroud_color").toString();
		qColor.setNamedColor(color);
		QJsonArray *array = new  QJsonArray;
		*array = obj_root->value("menu").toArray();
		for (auto obj : *array) {
			ButtonStruct buttonStruct;
			buttonStruct.text = obj.toObject().value("title").toString();
			buttonStruct.url = QString(BASE_URL)+obj.toObject().value("url").toString();
			buttonStruct.image = new QImage(obj.toObject().value("img").toString());
			buttonStruct.image_cover = new QImage(obj.toObject().value("img_cover").toString());
			buttonStructs << buttonStruct;
		}
		delete array;
	}
	else {
		QMessageBox::warning(nullptr, QString::fromLocal8Bit("错误"), QString::fromLocal8Bit("配置文件损坏"));
		delete obj_root;
		exit(1);
	}
	delete obj_root;

}