#include <cstdlib>

#include <QDebug>
#include <QLineEdit>
#include <QProcess>
#include <QString>
#include <qjsonobject.h>
#include <qnamespace.h>
#include <QDir>
#include <QCoreApplication>
#include <QRegularExpression>
#include <QJsonArray>

#include "mainwindow.h"
#include "../launcher/launcher.h"
#include "../backend/backend.h"
#include "../settings/settings.h"
#include "../../resources/ui_mainwindow.h"


MainWindow::MainWindow(QWidget *parent) : 
		QMainWindow(parent), 
		ui(new Ui::MainWindow), 
		process(new QProcess(this)), 
		launcher(new Launcher(this)), 
		backend(new Backend()),
		settings(new Settings())
{
	ui->setupUi(this);

	// Инициализация
	setWindowFlags(Qt::FramelessWindowHint);
	setAttribute(Qt::WA_TranslucentBackground);
	ui->StackedWidget->setCurrentWidget(ui->load);
	on_selected_profile_currentTextChanged(ui->selected_profile->currentText());


    backend->authWithToken([this](QString username, QString uuid, QString access_token) {
        if (username.isEmpty() || uuid.isEmpty() || access_token.isEmpty()) {
            ui->StackedWidget->setCurrentWidget(ui->auth);
        } else {
			ui->StackedWidget->setCurrentWidget(ui->main);
			ui->main_nickname_label->setText(username);
			this->username = username;
			this->uuid = uuid;
			this->access_token = access_token;
        }
    });

}


MainWindow::~MainWindow() { delete ui; }


void MainWindow::mousePressEvent(QMouseEvent *event) {
	if (ui->border_top->geometry().contains(event->pos())) {
		isDragging = true;
		ui->border_top->setCursor(Qt::SizeAllCursor);
		dragStartPosition =
			event->globalPosition().toPoint() - frameGeometry().topLeft();
		event->accept();
	}
}


void MainWindow::mouseMoveEvent(QMouseEvent *event) {
	if (isDragging) {
		move(event->globalPosition().toPoint() - dragStartPosition);
		event->accept();
	}
}


void MainWindow::mouseReleaseEvent(QMouseEvent *event) {
	isDragging = false;
	ui->border_top->setCursor(Qt::ArrowCursor);
	event->accept();
}


void MainWindow::on_auth_login_btn_clicked() {
    QString username = ui->auth_login_line->text();
    QString password = ui->auth_pass_line->text();

    backend->authWithPassword(
			username, 
			password, 
			[this](QString username, QString uuid, QString access_token) 
	{
        if (!username.isEmpty() && !uuid.isEmpty() && !access_token.isEmpty()) {
            ui->auth_status_label->setText("");
            ui->StackedWidget->setCurrentWidget(ui->main);
			ui->main_nickname_label->setText(username);

			this->username = username;
			this->uuid = uuid;
			this->access_token = access_token;
        } else {
            ui->auth_status_label->setText("Ошибка авторизации");
        }
    });
}


/* 
 * QComoBox не позволяет менять ориентацию текста
 * В этой функции происходит его центрирование через padding-left
 */
void MainWindow::on_selected_profile_currentTextChanged(QString text) {
    // Рассчёт padding-left
    QFontMetrics metrics(ui->selected_profile->font());
    int textWidth = metrics.horizontalAdvance(text);
    int comboBoxWidth = ui->selected_profile->width();
    int paddingLeft = (comboBoxWidth - textWidth) / 2;

    QString currentStyleSheet = ui->selected_profile->styleSheet();
    QString newStyleSheet = currentStyleSheet;
    if (currentStyleSheet.contains("padding-left:")) {
        newStyleSheet.replace(QRegularExpression("padding-left:\\s*\\d+px;?"), QString("padding-left: %1px;").arg(paddingLeft));
    } else {
        newStyleSheet += QString(" QComboBox { padding-left: %1px; }").arg(paddingLeft);
    }
    ui->selected_profile->setStyleSheet(newStyleSheet);
}


void MainWindow::on_settings_btn_clicked() {
	ui->StackedWidget->setCurrentWidget(ui->settings);

	QString selected_profile = ui->selected_profile->currentText();
	json_settings = settings->loadFromJson(selected_profile);

	ui->settings_ram->setText(json_settings["RAM"].toString());
	ui->settings_java_path->setText(json_settings["java_path"].toString());
	ui->settings_garbarge_collector->setCurrentText(json_settings["garbarge_collector"].toString());
	
}


void MainWindow::on_settings_back_btn_clicked() {
	ui->StackedWidget->setCurrentWidget(ui->main);
}


void MainWindow::on_logout_btn_clicked() {
	ui->StackedWidget->setCurrentWidget(ui->auth);
	QString session_cache = backend->getStateFilePath();
	QFile::remove(session_cache);
	ui->auth_login_line->setText("");
	ui->auth_pass_line->setText("");
}


void MainWindow::on_settings_apply_btn_clicked() {
	QJsonArray addition_settings;
	settings->saveToJson(
			ui->selected_profile->currentText(),
			ui->settings_ram->text(),
			ui->settings_java_path->text(),
			ui->settings_garbarge_collector->currentText(),
			addition_settings
			);
	ui->StackedWidget->setCurrentWidget(ui->main);
}


void MainWindow::on_start_btn_clicked() {
    launcher->startProcess(this->username, this->uuid, this->access_token);
}
