#ifndef AUDIO_QT_CAPTURER_H
#define AUDIO_QT_CAPTURER_H

#include <QAudioInput>
#include <QAudioOutput>
#include <QBuffer>
#include <QObject>
#include <QTimer>
#include <memory>
#include <QMutex>

#include "iaudiocapturer.h"

class AudioInfo : public QIODevice
{
    Q_OBJECT
public:
    AudioInfo(const QAudioFormat& format);

    void start();
    void stop();

    qreal level() const { return m_level; }

    qint64 readData(char* data, qint64 maxlen) override;
    qint64 writeData(const char* data, qint64 len) override;

private:
    const QAudioFormat m_format;
    quint32 m_maxAmplitude = 0;
    qreal m_level = 0.0; // 0.0 <= m_level <= 1.0

signals:
    void update();
};

class QtAudioCapturer : public QObject, public IAudioCapturer
{
    Q_OBJECT
public:
    explicit QtAudioCapturer(QObject* parent = nullptr);
    ~QtAudioCapturer() override;

    // IAudioCapturer接口实现
    bool Init(Type deviceType) override;
    bool Start() override;
    void Stop() override;
    const AudioFormat& GetFormat() const override;
    int readAudioData(char* buf, int maxLen) override;

private slots:
    void processAudioData();

private:
    bool initMicrophone();
    bool initSpeaker();
    float calculateVolume(const QByteArray& data);

private:
    Type m_deviceType;
    AudioFormat m_audioFormat;
    bool m_isRunning;

    // Qt音频相关
    QAudioFormat m_qtAudioFormat;
    QScopedPointer<AudioInfo> m_audioInfo;

    std::unique_ptr<QAudioInput> m_audioInput;
    QBuffer m_buffer;
    QTimer m_processTimer;
    QByteArray m_dataBuffer;
    QMutex m_mutex;
};

#endif // AUDIO_QT_CAPTURER_H
