// 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 <QWebSocket>
#include <chrono>

using namespace std::chrono;

class WebsocketClient : public QObject
{
    Q_OBJECT

    Q_PROPERTY(State state READ state NOTIFY stateChanged)
    Q_PROPERTY(QString stateDisplay READ stateDisplay NOTIFY stateChanged)

public:
    enum State {
        Connected,
        NotConnected,
    };

    static WebsocketClient &self(const QUrl &url = {}, int port = -1, const QString &clientId = {});

    State state() const;
    QString stateDisplay() const;

Q_SIGNALS:
    void stateChanged();

    /// Signal emited when an email was sent succesffully,
    void emailSentSuccessfully(const QString &id);

private Q_SLOTS:
    void slotConnected();
    void slotErrorOccurred(QAbstractSocket::SocketError error);
    void slotTextMessageReceived(QString message);

private:
    explicit WebsocketClient(const QUrl &url, int port, const QString &clientId);
    void reconnect();
    void registerServer();

    bool m_wasConnected = false;
    QWebSocket m_webSocket;
    QUrl m_url;
    const int m_port;
    QStringList m_emails;
    QString m_clientId;
    std::chrono::milliseconds m_delay = 2000ms;
    State m_state = NotConnected;
    QString m_stateDisplay;
};
