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

#include "controllers/emailcontroller.h"

#include <KLocalizedString>
#include <Libkleo/KeyCache>
#include <QApplication>
#include <QHttpServer>
#include <QHttpServerResponse>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkReply>
#include <QTimer>
#include <QUuid>

#include "qnam.h"
#include "webserver.h"
#include "websocketclient.h"

using namespace Qt::Literals::StringLiterals;
using namespace std::chrono;

#ifdef Q_OS_WINDOWS
#include <windows.h>
#endif

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    app.setQuitOnLastWindowClosed(false);

    KLocalizedString::setApplicationDomain(QByteArrayLiteral("gpgol"));

    QObject::connect(qnam, &QNetworkAccessManager::sslErrors, qnam, [](QNetworkReply *reply, const QList<QSslError> &) {
        reply->ignoreSslErrors();
    });

#ifdef Q_OS_WINDOWS
    if (AttachConsole(ATTACH_PARENT_PROCESS)) {
        freopen("CONOUT$", "w", stdout);
        freopen("CONOUT$", "w", stderr);
    }
#endif

    const auto clientId = QUuid::createUuid().toString(QUuid::WithoutBraces);

    WebServer server;
    server.run();
    if (!server.running()) {
        qWarning() << "Server failed to listen on a port.";
        return 1;
    }
    const auto port = server.port();

    WebsocketClient::self(QUrl(u"wss://localhost:5657/"_s), port, clientId);
    auto keyCache = Kleo::KeyCache::mutableInstance();
    keyCache->startKeyListing();

    return app.exec();
}
