import config from "../../config";

const Nls = require("alibabacloud-nls")
const sleep = (waitTimeInMs) => new Promise(resolve => setTimeout(resolve, waitTimeInMs))



class aliyunASR {
    constructor(options) {
        //配置项
        this.APPKEY = config.aliyun.APPKEY;
        this.TOKEN = config.aliyun.TOKEN;
        this.URL = config.aliyun.URL;

        this.speechRecognizer = null;
        this.isCanSendData = false;
        this.isCanStop = false;
    }

    //初始化
    async init(params) {
        if (!this.speechRecognizer) {
            this.speechRecognizer = new Nls.SpeechTranscription({
                url: this.URL,
                appkey: this.APPKEY,
                token: this.TOKEN
            });
        }
        this.speechRecognizer.on("started", (msg) => {
            console.log("【aliyun ASR】Client recv started:", msg)
        })

        this.speechRecognizer.on("changed", (msg) => {
            console.log("【aliyun ASR】识别变化时:", msg)
        })

        this.speechRecognizer.on("completed", (msg) => {
            console.log('【aliyun ASR】识别结束', msg);
            this.isCanSendData = false;
            this.onRecognitionComplete(msg);
        })

        this.speechRecognizer.on("closed", () => {
            console.log("【aliyun ASR】Client recv closed")
        })

        this.speechRecognizer.on("failed", (msg) => {
            console.log('【aliyun ASR】识别失败', msg);
            this.isCanSendData = false;
        })

        this.speechRecognizer.on("begin", (msg) => {
            console.log("【aliyun ASR】Client recv begin:", msg)
        })

        this.speechRecognizer.on("end", (msg) => {
            console.log('【aliyun ASR】一句话结束', msg);
            // resultText += res.result.voice_text_str;
            this.OnSentenceEnd(JSON.parse(msg));
        })
    }
    async getUrl() {

    }
    //连接
    async start() {
        await this.speechRecognizer.start(this.speechRecognizer.defaultStartParams(), true, 6000)
        this.isCanStop = true;
    }
    write(data) {
        this.speechRecognizer.sendAudio(data);
    }
    // 暂停识别，关闭连接
    stop() {
        if (this.isCanStop) {
            this.speechRecognizer.close();
        }
    }
    //识别结束
    onRecognitionComplete() {

    }
    //一句话结束
    OnSentenceEnd() {

    }
}

export default aliyunASR;