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

#include "webserver.h"
#include "controllers/emailcontroller.h"
#include <QJsonDocument>
#include <QJsonObject>

using namespace Qt::Literals::StringLiterals;

WebServer::WebServer(QObject *parent)
    : QObject(parent)
{
    m_server.route(u"/view"_s, &EmailController::viewEmailAction);
    m_server.route(u"/info"_s, &EmailController::infoEmailAction);
    m_server.route(u"/new"_s, &EmailController::newEmailAction);
    m_server.route(u"/forward"_s, &EmailController::forwardEmailAction);
    m_server.route(u"/reply"_s, &EmailController::replyEmailAction);
    m_server.route(u"/draft/"_s, &EmailController::draftAction);

    m_server.afterRequest([](QHttpServerResponse &&resp) {
#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0)
        auto h = resp.headers();
        h.append("Access-Control-Allow-Origin", "*");
        resp.setHeaders(std::move(h));
#else
        resp.setHeader("Access-Control-Allow-Origin", "*");
#endif
        return std::move(resp);
    });
}

void WebServer::run()
{
#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0)
    if (!m_tcpserver.listen(QHostAddress::Any) || !m_server.bind(&m_tcpserver)) {
        qWarning() << "Server failed to listen on a port.";
        m_running = false;
        return;
    }
    m_port = m_tcpserver.serverPort();
#else
    m_port = m_server.listen();
#endif
    if (!m_port) {
        qWarning() << "Server failed to listen on a port.";
        m_running = false;
        return;
    }
    qWarning() << u"Running on http://127.0.0.1:%1/ (Press CTRL+C to quit)"_s.arg(m_port);
    m_running = true;
}

int WebServer::port() const
{
    return m_port;
}

bool WebServer::running() const
{
    return m_running;
}
