// SPDX-FileCopyrightText: 2024 Open Mobile Platform LLC <community@omp.ru>
// SPDX-License-Identifier: BSD-3-Clause

#ifndef EARPIECEPLAYER_H
#define EARPIECEPLAYER_H

#include <QObject>
#include <QSharedPointer>
#include <QMediaPlayer>

#include <resource/qt5/policy/audio-resource.h>
#include <resource/qt5/policy/resource-set.h>

/*!
 * \brief EarpiecePlayer class provides a way to play the audio file by the earpiece.
 */
class EarpiecePlayer : public QObject
{
    Q_OBJECT
    Q_PROPERTY(bool resourceGranted READ resourceGranted NOTIFY resourceGrantedChanged)

public:
    explicit EarpiecePlayer(QObject *parent = nullptr);
    ~EarpiecePlayer();

    // Getters
    bool resourceGranted() const;

    void grantAudioResource();
    void releaseAudioResource();
    void play(const QString &audioFileUri);
    void stop();

private:
    ResourcePolicy::AudioResource *createAudioResource();
    void setupResourceSetHandlers();
    void setResourceGranted(const bool granted);

private slots:
    void handleMediaPlayerError(QMediaPlayer::Error error);
    void handleMediaPlayerStatusChanged(QMediaPlayer::MediaStatus status);

    void acquireAudioResource();
    void handleAudioResourceGranted();
    void handleAudioResourceReleased();
    void handleAudioResourceDenied();

private:
    QSharedPointer<QMediaPlayer> m_player{ nullptr };
    QSharedPointer<ResourcePolicy::ResourceSet> m_resourceSet{ nullptr };
    bool m_resourceGranted{ false };

signals:
    void resourceGrantedChanged();
    void playingFinished();
};

#endif // EARPIECEPLAYER_H
