#include "audiorecinfo.h"
#include <QtEndian>
#include <QDebug>
#include <QJsonObject>
#include <QJsonDocument>
#include <QThread>

#include <kylin-ai/ai-base/speech.h>

const qint64 MAX_AUDIO_BUF_LEN = 160 * 100;
static char g_audioBuffer[MAX_AUDIO_BUF_LEN] = {0};
static qint64 g_cntByte = 0;

AudioRecInfo::AudioRecInfo(QObject *paren) : QIODevice(paren) {}

AudioRecInfo::~AudioRecInfo() {}

qint64 AudioRecInfo::readData(char *data, qint64 maxlen)
{
    Q_UNUSED(data)
    Q_UNUSED(maxlen)
    return 0;
}

qint64 AudioRecInfo::writeData(const char *data, qint64 len)
{
    if (g_cntByte + len > MAX_AUDIO_BUF_LEN) {
//        QJsonObject jsonObject;
//        jsonObject["format"] = "pcm";
//        jsonObject["rate"] = 16000;
//        jsonObject["channel"] = 1;
//        const char *params = QJsonDocument(jsonObject).toJson(QJsonDocument::Indented);

        qDebug() <<  "writeData" << g_cntByte;
//        qDebug() << "data :" << g_audioBuffer;
        qDebug() << "thread" << QThread::currentThreadId();

//        SpeechResult result = speech_recognize_once_async(m_session, params, g_audioBuffer, g_cntByte);
        SpeechResult result = speech_continuous_recognition_write_audio_data_async(m_session, g_audioBuffer, g_cntByte);
        if (result != SPEECH_SUCCESS){
            qDebug() <<  "speech_continuous_recognition_write_audio_data_async error";
        }

        g_cntByte = 0;
    }

    for (qint64 i = 0; i < len; i++) {
        g_audioBuffer[g_cntByte + i] = data[i];
    }

    g_cntByte += len;

    return len;
}

