// 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) {
        resp.setHeader("Access-Control-Allow-Origin", "*");
        return std::move(resp);
    });
}

void WebServer::run()
{
    m_port = m_server.listen();
    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;
}
