// SPDX-FileCopyrightText: 2024 UnionTech Software Technology Co., Ltd.
//
// SPDX-License-Identifier: GPL-3.0-or-later
#include "asriflymodel.h"
#include "iatiflymodel.h"

#include <QRegularExpression>

UOSAI_USE_NAMESPACE

AsrIflyModel::AsrIflyModel(const QString &id, QObject *parent)
    :  AsrModel(id, parent)
{
    connect(&decoder, SIGNAL(bufferReady()), this, SLOT(bufferReady()));
    connect(&decoder, SIGNAL(finished()), this, SLOT(bufferfinish()));
}

QString AsrIflyModel::startAsr(const QVariantMap &param)
{
    QString filePath = param["filePath"].toString();
    QAudioFormat format;
    format.setSampleRate(16000);
    format.setChannelCount(1);
#ifdef COMPILE_ON_QT6
    format.setSampleFormat(QAudioFormat::SampleFormat::Int16);
#else
    format.setSampleSize(16);
    format.setCodec("audio/pcm");
    format.setByteOrder(QAudioFormat::LittleEndian);
    format.setSampleType(QAudioFormat::SignedInt);
#endif

#ifdef COMPILE_ON_QT6
    decoder.setSource(filePath); // 设置音频文件路径
#else
    decoder.setSourceFilename(filePath); // 设置音频文件路径
#endif

    decoder.setAudioFormat(format);
    if (m_iatModel == nullptr) {
        m_iatModel = new IatIflyModel();
        connect(m_iatModel, &IatIflyModel::textReceived, this, &AsrIflyModel::iatSlot, Qt::QueuedConnection);
    }
    m_iatModel->openServer();
    decoder.start(); // 开始解码
    return "000000";
}

void AsrIflyModel::bufferReady() {
    QAudioBuffer buffer = decoder.read();
    QByteArray pcmData;
    if (buffer.isValid()) {
        pcmData.append(static_cast<const char*>(buffer.constData<char>()), buffer.byteCount());
    }

    m_iatModel->sendData(pcmData);
}

void AsrIflyModel::bufferfinish() {
    m_iatModel->inputEnd();
}

void AsrIflyModel::iatSlot(QString result, bool finish)
{
    if (finish) {
        QJsonDocument doc;
        QJsonObject json = doc.object();
        json["code"] = "000000";
        json["failType"] = 0;
        json["status"] = 4;
        json["descInfo"] = "success";
        json["text"] = result;
        QString msg = QString(QJsonDocument(json).toJson());
        emit onNotify(msg);
        qInfo()<<"onNotify:"<<msg;
    }
}

void AsrIflyModel::stopAsr()
{
    if (m_iatModel != nullptr) {
        m_iatModel->cancel();
        disconnect(m_iatModel,SIGNAL(textReceived(QString,bool)),this,SLOT(iatSlot(QString, bool)));
        m_iatModel->deleteLater();
    }
}

