// SPDX-FileCopyrightText: 2023 g10 code GmbH
// SPDX-Contributor: Carl Schwan <carl.schwan@gnupg.com>
// SPDX-License-Identifier: GPL-2.0-or-later

#include "staticcontroller.h"

#include "http_debug.h"
#include <QDebug>
#include <QFile>

using namespace Qt::Literals::StringLiterals;

QHttpServerResponse StaticController::homeAction(const QHttpServerRequest &)
{
    QFile file(u":/web/index.html"_s);
    if (!file.open(QIODeviceBase::ReadOnly)) {
        qCWarning(HTTP_LOG) << file.errorString();
        return QHttpServerResponse(QHttpServerResponder::StatusCode::NotFound);
    }

    return QHttpServerResponse("text/html", file.readAll());
}

QHttpServerResponse StaticController::assetsAction(QString fileName, const QHttpServerRequest &)
{
    QFile file(u":/web/assets/"_s + fileName);
    if (!file.open(QIODeviceBase::ReadOnly)) {
        qCWarning(HTTP_LOG) << file.errorString();
        return QHttpServerResponse(QHttpServerResponder::StatusCode::NotFound);
    }

    if (fileName.endsWith(u".png"_s)) {
        return QHttpServerResponse("image/png", file.readAll());
    } else if (fileName.endsWith(u".js"_s)) {
        return QHttpServerResponse("text/javascript", file.readAll());
    } else if (fileName.endsWith(u".css"_s)) {
        return QHttpServerResponse("text/css", file.readAll());
    }
    return QHttpServerResponse("text/plain", file.readAll());
}
