/*******************************************************************************
 *
 * SPDX-FileCopyrightText: 2024 Open Mobile Platform LLC <community@omp.ru>
 * SPDX-License-Identifier: MIT
 *
 ******************************************************************************/

#ifndef RM_LIB_TASK_MESSAGING_H
#define RM_LIB_TASK_MESSAGING_H

#include "error.h"
#include "global.h"

#include <QObject>
#include <QScopedPointer>
#include <QString>

class QJsonObject;

namespace RuntimeManager {

class TaskMessagingPrivate;
/**
 * @brief Manage a background task_messaging
 * @class TaskMessaging task_messaging.h <RuntimeManager/TaskMessaging>
 *
 * The TaskMessaging class allows applications to start background task_messagings, track
 * their execution, and stop them.
 */
class RM_EXPORT TaskMessaging: public QObject
{
    Q_OBJECT

public:
    enum State {
        /** The socket is disconnected */
        Disconnected,
        /** The socket is connecting */
        Connecting,
        /** The socket is connected */
        Connected,
        /** The connection is closing down*/
        Closing,
    };

    /**
     * Constructor.
     *
     * Use this on the application side, to establish a connection to the
     * background task.
     *
     * @param socketPath The path to the socket, as returned by
     *        Task::socketPath()
     */
    TaskMessaging(const QString &socketPath, QObject *parent = Q_NULLPTR);

    /**
     * Constructor.
     *
     * Use this on the background task side, to receive a connection from the
     * application. When the application connects, the stateChanged() signal
     * will be emitted.
     *
     * @param serverSocket The file descriptor of the socket, as returned by
     *        RuntimeDispatcher::localServerSocket()
     */
    TaskMessaging(qintptr serverSocket, QObject *parent = Q_NULLPTR);
    ~TaskMessaging();

    /**
     * Sends a message to the peer.
     *
     * This message sends a message to the peer, in a non-blocking way.
     *
     * @param message The JSON message.
     *
     * @return false if disconnected.
     */
    bool sendMessage(const QJsonObject &message);

    /**
     * Get the current state of the task_messaging.
     *
     * @return the state of the task_messaging.
     */
    State state() const;

Q_SIGNALS:
    /**
     * Emitted when the connection state changes.
     *
     * @param state Tell the current state of the connection.
     *
     * @sa state()
     */
    void stateChanged(State state);

    /**
     * Emitted when a message has been received.
     *
     * @param message The JSON message.
     */
    void messageReceived(const QJsonObject &message);

private:
    Q_DECLARE_PRIVATE(TaskMessaging)
    QScopedPointer<TaskMessagingPrivate> d_ptr;
};

} // namespace RuntimeManager

#endif // RM_LIB_TASK_MESSAGING_H
