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

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



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

        this.format = options.format||'pcm';
        this.sampleRate = options.sampleRate||'16000';
    }

    async speechRecognition(data) {
        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/"+this.format+";rate="+this.sampleRate,
        };

         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;