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

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



class asyncAliyunASR {
    constructor(options) {
        //配置项
        this.APPKEY = options.token?.APPKEY||config.aliyun.APPKEY;
        this.TOKEN = options.token?.TOKEN||config.aliyun.TOKEN;
        this.URL = options.token?.URL||config.aliyun.AsyncURL;

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

    async speechRecognition(data, param) {
        var requestUrl = this.URL + '?appkey=' + this.APPKEY + '&format=' + this.format + '&sample_rate=' + this.sampleRate;
        if (this.enablePunctuationPrediction) {
            requestUrl = requestUrl + '&enable_punctuation_prediction=' + 'true';
        }
        if (this.enableInverseTextNormalizationF) {
            requestUrl = requestUrl + '&enable_inverse_text_normalization=' + 'true';
        }
        if (this.enableVoiceDetection) {
            requestUrl = requestUrl + '&enable_voice_detection=' + 'true';
        }

        /**
       * 设置HTTPS请求头部
      */
        var httpHeaders = {
            'X-NLS-Token': this.TOKEN,
            'Content-type': 'application/octet-stream',
            'Content-Length': data.length
        };

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

    }
}

export default asyncAliyunASR;