#pragma once

#include <condition_variable>
#include <portaudio.h>
#include <queue>

#include "AudioPacketsComparator.hpp"
#include "../base/BaseEvent.hpp"


namespace drp::event {


class AudioEvent : public BaseEvent {
public:
    AudioEvent();
    ~AudioEvent() override;

    void updateAudioStream(int channels, std::uint32_t sampleFormat, double sampleRate);
    void loopPlay();

    void handle(
        Context& context,
        std::vector<std::uint8_t>& data,
        const sockaddr_storage& fromAddress,
        socklen_t fromAddressLength
    ) override;

private:
    std::thread playerThread;

    PaStream* stream;
    int streamChannels;
    std::uint32_t streamSampleFormat;
    double streamRate;
    std::priority_queue<packet::audio::AudioPacketData, std::vector<packet::audio::AudioPacketData>, AudioPacketsComparator> audioQueue;

    std::mutex audioMutex;
    std::unique_lock<std::mutex> audioLock;
    std::condition_variable audioCondition;
};


}
