// SPDX-License-Identifier: GPL-3.0-only
/*
 *  Luna Launcher - Minecraft Launcher
 *  Copyright (C) 2025 AndreaFrederica <andreafrederica@outlook.com>
*/
#include "ServerEulaPage.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QFile>
#include <QTextStream>
#include <QMessageBox>

ServerEulaPage::ServerEulaPage(ServerInstance *instance, QWidget *parent)
    : QWidget(parent), m_instance(instance)
{
    auto layout = new QVBoxLayout(this);

    auto infoLabel = new QLabel(tr("By changing the setting below to TRUE you are indicating your agreement to Mojang's EULA (https://aka.ms/MinecraftEULA)."), this);
    infoLabel->setWordWrap(true);
    layout->addWidget(infoLabel);

    m_eulaCheckbox = new QCheckBox(tr("I agree to the Minecraft End User License Agreement"), this);
    layout->addWidget(m_eulaCheckbox);

    auto eulaLabel = new QLabel(tr("EULA file content:"), this);
    layout->addWidget(eulaLabel);

    m_eulaText = new QTextEdit(this);
    m_eulaText->setReadOnly(true);
    m_eulaText->setMaximumHeight(150);
    layout->addWidget(m_eulaText);

    layout->addStretch();

    connect(m_eulaCheckbox, &QCheckBox::toggled, this, &ServerEulaPage::updateEulaPreview);
}

ServerEulaPage::~ServerEulaPage() {}

QString ServerEulaPage::displayName() const { return tr("EULA"); }
QIcon ServerEulaPage::icon() const { return QIcon::fromTheme("settings"); }
QString ServerEulaPage::id() const { return "server-eula"; }
QString ServerEulaPage::helpPage() const { return "Server-EULA"; }
bool ServerEulaPage::shouldDisplay() const { return true; }

void ServerEulaPage::openedImpl()
{
    loadEula();
}

void ServerEulaPage::loadEula()
{
    QString eulaPath = m_instance->instanceRoot() + "/eula.txt";
    QFile eulaFile(eulaPath);

    if (eulaFile.exists() && eulaFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        m_fileExistedAtLoad = true;
        QTextStream in(&eulaFile);
        QString content = in.readAll();
        m_eulaText->setPlainText(content);
        eulaFile.close();

        // Check if eula=true exists in the file
        bool agreed = content.contains("eula=true", Qt::CaseInsensitive);
        m_initialAgreed = agreed;
        m_eulaCheckbox->setChecked(agreed);
    } else {
        m_fileExistedAtLoad = false;
        // Default EULA text
        QString defaultEula = "#By changing the setting below to TRUE you are indicating your agreement to our EULA (https://aka.ms/MinecraftEULA).\n"
                             "#Generated by Luna Launcher\n"
                             "eula=false";
        m_eulaText->setPlainText(defaultEula);
        m_initialAgreed = false;
        m_eulaCheckbox->setChecked(false);
    }
}

void ServerEulaPage::updateEulaPreview()
{
    QString currentText = m_eulaText->toPlainText();

    if (m_eulaCheckbox->isChecked()) {
        currentText.replace("eula=false", "eula=true");
    } else {
        currentText.replace("eula=true", "eula=false");
    }

    m_eulaText->setPlainText(currentText);
}

bool ServerEulaPage::apply()
{
    QString eulaPath = m_instance->instanceRoot() + "/eula.txt";
    // Build new content
    QString newContent;
    newContent += "#By changing the setting below to TRUE you are indicating your agreement to our EULA (https://aka.ms/MinecraftEULA).\n";
    newContent += "#Generated by Luna Launcher\n";
    newContent += QString("eula=%1\n").arg(m_eulaCheckbox->isChecked() ? "true" : "false");

    // If file existed when page loaded and user didn't change the checkbox, never overwrite
    if (m_fileExistedAtLoad && (m_eulaCheckbox->isChecked() == m_initialAgreed)) {
        return true;
    }

    // Read old content first to avoid truncation
    QByteArray oldBytes;
    if (QFileInfo::exists(eulaPath)) {
        QFile oldFile(eulaPath);
        if (oldFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
            oldBytes = oldFile.readAll();
            oldFile.close();
        }
    }

    if (oldBytes == newContent.toUtf8()) {
        return true;
    }

    QFile eulaFile(eulaPath);
    if (!eulaFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::critical(this, tr("Error"), tr("Failed to save eula.txt"));
        return false;
    }
    QTextStream out(&eulaFile);

    // Write EULA file with proper format
    out << newContent;

    eulaFile.close();
    return true;
}
