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

const sleep = (waitTimeInMs) => new Promise(resolve => setTimeout(resolve, waitTimeInMs))
const axios = require('axios');



class asyncBaiduASR {
    constructor(options) {
        //配置项
        this.appId=config.baidu.appId ;
        this.appKey= config.baidu.appKey;
        this.secretKey=config.baidu.secretKey;
        this.devPID= config.baidu.devPID;
        this.URI = config.baidu.AsyncURL;
        this.tokenURL=config.baidu.tokenURL;

        this.format = 'pcm';
        this.sampleRate = '16000';
        this.enablePunctuationPrediction = true;
        this.enableInverseTextNormalization = true;
        this.enableVoiceDetection = false;
    }

    async speechRecognition(data, param) {
        var result={};
        try {
        //获取TOKEN
        var options = {
            url: this.tokenURL+"?grant_type=client_credentials&client_id="+this.appKey+"&client_secret="+this.secretKey,
            method: 'GET',
        };
        var tokenResult =await axios(options);
        var token=tokenResult.data.refresh_token;
        console.log("【Baidu Async ASR】 GET TOKEN:",token);
        //BAIDU ASR
        var requestUrl = this.URI + '?&cuid=tx-test-001' + '&token=' + token;
        /**
       * 设置HTTPS请求头部
      */
        var httpHeaders = {
            'Content-type': 'audio/pcm;rate=16000',
        };

         options = {
            url: requestUrl,
            method: 'POST',
            headers: httpHeaders,
            data: data
        };
          result = await axios(options)
        } catch (e) {
            console.error("【BAIDU ASR】初始化接口内部错误",e);
            result.statusText=e;
            result.status=500;
        }
        return result;
    }
}

export default asyncBaiduASR;