// SPDX-License-Identifier: GPL-3.0-only
/*
 *  Luna Launcher - Minecraft Launcher
 *  Copyright (C) 2025 AndreaFrederica <andreafrederica@outlook.com>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, version 3.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

#include "Nide8AuthDownloadTask.h"

#include <QDir>
#include <QFileInfo>

#include "Application.h"
#include "FileSystem.h"
#include "minecraft/auth/Nide8Auth.h"

Nide8AuthDownloadTask::Nide8AuthDownloadTask(LaunchTask* parent) : LaunchStep(parent)
{
    m_network.reset(new QNetworkAccessManager(this));
    m_jarPath = Nide8Auth::instance().getLocalPath();
}

bool Nide8AuthDownloadTask::abort()
{
    if (m_jarReply && m_jarReply->isRunning()) {
        m_jarReply->abort();
        return true;
    }
    return false;
}

void Nide8AuthDownloadTask::executeTask()
{
    setStatus(tr("Checking nide8auth.jar..."));

    // Check if we already have a valid cached version
    QFileInfo fileInfo(m_jarPath);
    if (fileInfo.exists() && fileInfo.size() > 50 * 1024) {
        // File exists and is larger than 50KB, consider it valid
        emitSucceeded();
        return;
    }

    // Need to download
    QString jarUrl = "https://login.mc-user.com:233/index/jar";

    QNetworkRequest request((QUrl(jarUrl)));
    request.setRawHeader("User-Agent", APPLICATION->getUserAgent().toUtf8());

    m_jarReply = m_network->get(request);
    connect(m_jarReply, &QNetworkReply::finished, this, &Nide8AuthDownloadTask::downloadJarFinished);
    connect(m_jarReply, &QNetworkReply::downloadProgress, this, [this](qint64 received, qint64 total) {
        m_totalSize = total;
        if (total > 0) {
            setProgress(received, total);
        }
        setDetails(tr("%1 / %2").arg(received / 1024).arg(total / 1024) + " KB");
    });
}

void Nide8AuthDownloadTask::downloadJarFinished()
{
    if (m_jarReply->error() != QNetworkReply::NoError) {
        emitFailed(tr("Failed to download nide8auth.jar: %1").arg(m_jarReply->errorString()));
        m_jarReply->deleteLater();
        m_jarReply = nullptr;
        return;
    }

    QByteArray jarData = m_jarReply->readAll();
    m_jarReply->deleteLater();
    m_jarReply = nullptr;

    // Check if we got any data
    if (jarData.isEmpty()) {
        emitFailed(tr("Downloaded nide8auth.jar is empty"));
        return;
    }

    // Ensure parent directory exists
    QDir().mkpath(QFileInfo(m_jarPath).absolutePath());

    // Write to file
    QFile file(m_jarPath);
    if (!file.open(QIODevice::WriteOnly)) {
        emitFailed(tr("Failed to open nide8auth.jar for writing: %1").arg(file.errorString()));
        return;
    }

    file.write(jarData);
    file.close();

    qDebug() << "Successfully downloaded nide8auth.jar to" << m_jarPath;
    emitSucceeded();
}
