import { WebSocket } from 'ws';

function guid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

export default class SpeechRecognizer {
    constructor(params) {
        this.socket = null;
        //配置项
        this.appId = params.appId;
        this.appKey = params.appKey;
        this.devPID = params.devPID;
        this.URI = params.URI;
        this.isClose = true;
    }

    sendStartFrame() {
        //发送开始参数帧
        var startFrame =
        {
            "type": "START",
            "data": {
                "appid": this.appId,
                "appkey": this.appKey,
                "dev_pid": this.devPID,
                // "lm_id": xxxx, 
                "cuid": "cuid-1",
                "format": "pcm",
                "sample": 16000
            }
        }
        console.log("【百度ASR】send start FRAME :=====>>>", startFrame);
        this.socket.send(JSON.stringify(startFrame));
    }
    sendAudioFrames(data) {
        // TODO 实时发送音频数据帧
        console.log("【百度ASR】send data FRAME :=====>>>", data);
        this.socket.send(data);

    }
    sendFinishFrame() {
        // 发送结束帧
        var finishFrame =
        {
            "type": "FINISH"
        }
        console.log("【百度ASR】send finish FRAME  :=====>>>", finishFrame);
        this.socket.send(JSON.stringify(finishFrame));
        this.OnRecognitionComplete(finishFrame);
    }
    async start() {
        if (!this.URI) {
            this.OnError('鉴权失败');
            return;
        }
        const url = this.URI + "?sn=" + guid();
        console.log("【百度ASR】 socket URL :=====>>>", url);
        this.socket = new WebSocket(url);
        this.socket.onopen = (e) => { // 连接建立时触发
            this.isClose = false;
            this.sendStartFrame();
        };
        this.socket.onmessage = (e) => { // 连接建立时触发
            // 接收识别结果
            const response = JSON.parse(e.data);
            if (response.type == "HEARTBEAT") {
                console.log("【百度ASR】receive heartbeat:=====>>>", response);
            } else {
                // console.log("【百度ASR】receive text:=====>>>", response);
                if (response.type == "MID_TEXT") {
                    this.OnRecognitionResultChange(response);
                } else if (response.type == "FIN_TEXT") {
                    this.OnSentenceEnd(response);
                }
            }
        };
        this.socket.onclose = (e) => {
            console.log("【百度ASR】websocket event closing :", e.code, e.reason);
            this.sendFinishFrame();
            this.socket.close(1000, "");
            this.isClose = true;
        };
        this.socket.onerror = (e) => {
            console.log("【百度ASR】websocket event error :", e.code, e.reason);
            this.sendFinishFrame();
            this.socket.close(1000, "");
            this.isClose = true;
        }

    }
    // 发送数据
    write(data) {
        if (!this.socket || this.socket.readyState !== 1) {
            this.OnError('连接未建立，请稍后发送数据！')
            return
        }
        this.sendAudioFrames(data);
    };

    stop() {
        if (this.socket && this.socket.readyState === 1) {
          this.sendFinishFrame();
        } else {
          this.OnError('连接未建立或连接已关闭');
          if (this.socket && this.socket.readyState === 1) {
            this.socket.close();
          }
        }
      }
    // 识别结果发生变化的时候
    OnRecognitionResultChange() {

    }
    // 一句话结束的时候
    OnSentenceEnd() {

    }
    // 识别结束的时候
    OnRecognitionComplete() {

    }
    // 识别失败
    OnError() {

    }
}