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

#pragma once

#include <QByteArray>
#include <QList>
#include <QObject>
#include <QSslError>

QT_FORWARD_DECLARE_CLASS(QWebSocketServer)
QT_FORWARD_DECLARE_CLASS(QWebSocket)

class WebsocketRequestBackend;
class QHttpServer;

class WebServer : public QObject
{
    Q_OBJECT
public:
    /// Get singleton instance of WebServer
    static WebServer &self();

    /// WebServer destructor.
    ~WebServer() override;

    /// Start web server.
    bool run();

    /// is a valid WebServer instance
    bool isValid() const;

    bool sendMessageToWebClient(const QString &email, const QByteArray &payload);
    bool sendMessageToNativeClient(const QString &email, const QByteArray &payload);

private Q_SLOTS:
    void onNewConnection();
    void processTextMessage(QString message);
    void processBinaryMessage(QByteArray message);
    void socketDisconnected();

private:
    WebServer();

    enum class Command {
        Undefined, ///< Undefined command.
        Register, ///< Registration of a client (native or web).
        EmailSent, ///< Confirmation that an email was sent.
    };

    enum SpecialValues {
        Port = 5656,
        WebSocketPort = 5657,
    };

    void processCommand(Command command, const QJsonObject &arguments, QWebSocket *socket);

    QHttpServer *const m_httpServer;
    QWebSocketServer *const m_webSocketServer;
    QList<QWebSocket *> m_clients;
    QHash<QString, QWebSocket *> m_webClientsMappingToEmail;
    QHash<QString, QWebSocket *> m_nativeClientsMappingToEmail;

    static WebServer s_instance;
};
