import Recorder from 'recorder-core';
import 'recorder-core/src/engine/pcm';
import 'recorder-core/src/engine/wav';
import WebSocketConnectMethod from './wsconnecter';

let wsconnecter;
let rec;
export const audioService = setResult => {
    // 判断当前访问协议，匹配websocket连接
    //  const protocol = window.location.protocol.replace(':', '');
    //  const url = protocol === 'http' ? 'ws://asr.ngsk.tech:7000/' : 'wss://asr.ngsk.tech:7000/';
    // const url = 'wss://asr.ngsk.tech:7001/';
    const url = 'wss://medicalai.ngsk.tech:7001/api/v1/ws';

    // 连接; 定义socket连接类对象与语音对象
    let sampleBuf = new Int16Array();
    let rec_text = '';
    let offline_text = '';
    let isRec = false;

    // 语音识别结果; 对jsonMsg数据解析,将识别结果附加到编辑框中
    function getJsonMessage(jsonMsg) {
        console.log(`message: ${JSON.parse(jsonMsg.data).text}`);
        const rectxt = `${JSON.parse(jsonMsg.data).text}`;
        const asrmodel = JSON.parse(jsonMsg.data).mode;
        const {is_final} = JSON.parse(jsonMsg.data);
        if (asrmodel === '2pass-offline' || asrmodel === 'offline') {
            offline_text = `${offline_text + rectxt.replace(/ +/g, '')}\n`; // handleWithTimestamp(rectxt,timestamp); //rectxt; //.replace(/ +/g,"");
            rec_text = offline_text;
        } else {
            rec_text += rectxt; // .replace(/ +/g,"");
        }
        if (rec_text.length > 0) {
            setResult(rec_text);
        }

        console.log(`offline_text: ${asrmodel},${offline_text}`);
        console.log(`rec_text: ${rec_text}`);
    }

    // 连接状态响应
    function getConnState(connState) {
        if (connState === 2) {
            stop();
            console.log('connection error');
        }
    }

    // 开始录音
    function record() {
        // 录音; 定义录音对象,wav格式
        rec = Recorder({
            type: 'pcm',
            bitRate: 16,
            sampleRate: 16000,
            onProcess: recProcess
        });
        rec.open(function () {
            rec.start();
            console.log('开始');
        });
    }

    // 识别启动、停止、清空操作
    function connect() {
        // 控件状态更新
        wsconnecter = new WebSocketConnectMethod({
            msgHandle: getJsonMessage,
            stateHandle: getConnState,
            url
        });

        // 启动连接
        const ret = wsconnecter.wsStart();
        // 1 is ok, 0 is error
        if (ret === 1) {
            isRec = true;
            record();
            return 1;
        }
        return 0;
    }

    function stop() {
        rec_text = '';
        offline_text = '';
        if (sampleBuf.length > 0) {
            wsconnecter.wsSend(sampleBuf);
            console.log(`sampleBuf.length${sampleBuf.length}`);
            sampleBuf = new Int16Array();
        }
        // 控件状态更新
        isRec = false;
        const request = {
            chunk_interval: 10,
            chunk_size: [5, 10, 5],
            is_speaking: false,
            mode: '2pass',
            wav_name: 'h5'
        };
        wsconnecter.wsSend(JSON.stringify(request));
        // wait 3s for asr result

        rec.stop(
            function (blob, duration) {
                console.log(blob);
            },
            function (errMsg) {
                console.log(`errMsg: ${errMsg}`);
            }
        );
        setTimeout(function () {
            console.log('call stop ws!');
            wsconnecter.wsStop();
        }, 1000);
    }

    function recProcess(buffer, powerLevel, bufferDuration, bufferSampleRate, newBufferIdx, asyncEnd) {
        if (isRec === true) {
            const data_48k = buffer[buffer.length - 1];

            const array_48k = new Array(data_48k);
            const data_16k = Recorder.SampleData(array_48k, bufferSampleRate, 16000).data;

            sampleBuf = Int16Array.from([...sampleBuf, ...data_16k]);
            const chunk_size = 960; // for asr chunk_size [5, 10, 5]
            while (sampleBuf.length >= chunk_size) {
                const sendBuf = sampleBuf.slice(0, chunk_size);
                sampleBuf = sampleBuf.slice(chunk_size, sampleBuf.length);
                wsconnecter.wsSend(sendBuf);
            }
        }
    }

    return {
        stop,
        record,
        connect
    };
};
