import { WebSocket } from 'ws';

export default class SpeechRecognizer {
    constructor(params) {
        this.socket = null;
        //配置项
        this.endpoint = params.endpoint,
            this.projectId = params.projectId,
            this.token = params.token;
        this.isClose = true;
    }

    sendStartFrame() {
        //发送开始参数帧
        var startFrame = {
            "command": "START",
            "config":
            {
                "audio_format": "pcm16k16bit",
                "property": "chinese_16k_common",
                "add_punc": "yes",
                "vad_tail": 400,
                "interim_results": "yes",
                "need_word_info": "yes"
            }
        }
        console.log("【HUAWEI ASR】send start FRAME :=====>>>", startFrame);
        this.socket.send(JSON.stringify(startFrame));
    }
    sendAudioFrames(arraybuffer) {
        // TODO 实时发送音频数据帧
        // console.log("【HUAWEI ASR】send data FRAME :=====>>>", data);
        this.socket.binaryType = 'arraybuffer';
        this.socket.send(arraybuffer);

    }
    sendFinishFrame() {
        // 发送结束帧
        var finishFrame = {
            "command": "END",
            "cancel": false
        }
        console.log("【HUAWEI ASR】send finish FRAME  :=====>>>", finishFrame);
        this.socket.send(JSON.stringify(finishFrame));
        this.OnRecognitionComplete(finishFrame);
    }
    async start() {
        if (!this.endpoint || !this.projectId || !this.token) {
            this.OnError('鉴权失败');
            return;
        }
        const url = "wss://" + this.endpoint + "/v1/" + this.projectId + "/rasr/continue-stream";
        console.log("【HUAWEI ASR】 socket URL :=====>>>", url);
        this.socket = new WebSocket(url, {
            headers: {
                "X-Auth-Token": this.token
            }
        });
        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("【HUAWEI ASR】receive heartbeat:=====>>>", response);
            } else {
                if (response.resp_type == "ERROR") {
                    console.log("【HUAWEI ASR】error text:=====>>>", response);
                } else if (response.resp_type == "RESULT") {
                    if(response.segments[0].is_final){
                        this.OnSentenceEnd(response);
                    }else{
                        this.OnRecognitionResultChange(response);
                    }
                } else {
                    console.log("【HUAWEI ASR】other text:=====>>>", response);
                }

            }
        };
        this.socket.onclose = (e) => {
            console.log("【HUAWEI ASR】websocket event closing :", e.code, e.reason);
            this.sendFinishFrame();
            this.socket.close(1000, "");
            this.isClose = true;
        };
        this.socket.onerror = (e) => {
            console.log("【HUAWEI ASR】websocket event error :", e);
            this.sendFinishFrame();
            this.socket.close(1000, "");
            this.isClose = true;
        }

    }
    // 发送数据
    write(data) {
        if (!this.socket || this.socket.readyState !== 1) {
            this.OnError('连接未建立，请稍后发送数据！')
            return
        }
        // console.log("发送音频二进制",data);
        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() {

    }
}