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

class EmailViewer;

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 = {}, const QString &clientId = {});

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

    /// \params fromEmail The email address who should send this EWS request.
    /// \params requestId Identifier of the request, will be send back in ewsResponseReceived
    /// \params requestBody The SOAP request body.
    bool sendEWSRequest(const QString &fromEmail, const QString &requestId, const QString &requestBody);

    void sendViewerClosed(const QString &fromEmail);
    void sendViewerOpened(const QString &fromEmail);

Q_SIGNALS:
    void stateChanged();

    void ewsResponseReceived(const QString &requestId, const QString &responseBody);

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

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

    bool m_wasConnected = false;
    QWebSocket m_webSocket;
    QUrl m_url;
    QStringList m_emails;
    QString m_clientId;
    std::chrono::milliseconds m_delay = 2000ms;
    State m_state = NotConnected;
    QString m_stateDisplay;
    QPointer<EmailViewer> m_emailViewer;
};
