import $i18n from '../../../locales/i18n.js';
import { useCallback, useRef, useState } from 'react';
import { v4 as uuidv4 } from 'uuid';
import Recorder from 'recorder-core';
import { CnMessage } from '@cainiaofe/cn-ui';
import useTimer from './use-timer';
const hideRecorderLog = true;
if (hideRecorderLog) {
    Recorder.CLog = () => { };
}
const WEBSOCKET_URL = 'wss://flamingo.cainiao-inc.com/ws/asr';
const textBuffer = {
    messageId: '',
    current: '',
    data: [],
};
/** 获取到文本后的填充模式 */
export var FILL_MODE;
(function (FILL_MODE) {
    /** 填充到消息 */
    FILL_MODE["MESSAGE"] = "message";
    /** 填充到输入框 */
    FILL_MODE["INPUT"] = "input";
})(FILL_MODE || (FILL_MODE = {}));
/** 录音状态 */
export var RECORD_STATUS;
(function (RECORD_STATUS) {
    /** 初始 */
    RECORD_STATUS[RECORD_STATUS["DEFAULT"] = 1] = "DEFAULT";
    /** 录音中 */
    RECORD_STATUS[RECORD_STATUS["RECORDING"] = 2] = "RECORDING";
    /** 暂停 */
    RECORD_STATUS[RECORD_STATUS["PAUSED"] = 3] = "PAUSED";
})(RECORD_STATUS || (RECORD_STATUS = {}));
export default function useRecord({ onRecordMessage, onStartRecord, onContinueRecord, onPauseRecord, onStopRecord, }) {
    const [recordStatus, setRecordStatus] = useState(RECORD_STATUS.DEFAULT);
    const { startTimer, stopTimer, resetTimer, formattedTime } = useTimer();
    const [conversationId, setConversationId] = useState('');
    const [keywords, setKeywords] = useState([]);
    const [fillMode, setFillMode] = useState('');
    // recorder-core的实例
    const recorderRef = useRef(null);
    // ws连接，用于实时转译接口
    const wsRef = useRef(null);
    let sampleBuf = new Int16Array();
    const highlightText = useCallback(async (messageId, text) => {
        if (!text)
            return;
        // TODO: 待实现文本替换
        onRecordMessage({
            id: messageId,
            text,
            method: 'update',
            format: true,
        });
    }, [keywords, onRecordMessage]);
    const onSocketMessage = useCallback((event, _fillMode) => {
        if (typeof event.data === 'string' && event.data.indexOf('[Info]') >= 0) {
            return;
        }
        let msg = null;
        try {
            msg = JSON.parse(event.data);
        }
        catch (error) {
            return;
        }
        const { text } = msg;
        if (!text)
            return;
        // 如果当前没有消息，则将当前消息推入消息列表
        if (!textBuffer.data.length) {
            textBuffer.data.push(msg);
        }
        else if (textBuffer.data[textBuffer.data.length - 1].isSentenceEnd) {
            textBuffer.data.push(msg);
        }
        else {
            textBuffer.data[textBuffer.data.length - 1].text = text;
            textBuffer.data[textBuffer.data.length - 1].isSentenceEnd = msg.isSentenceEnd;
        }
        // 将data中的text拼接成当前文本
        textBuffer.current = textBuffer.data.map((item) => item.text).join('');
        // 填充文本模式，直接抛出事件
        if (_fillMode === FILL_MODE.INPUT) {
            onRecordMessage({
                text: textBuffer.current,
                method: 'setInputText',
            });
        }
        else if (!textBuffer.messageId) {
            const messageId = uuidv4();
            textBuffer.messageId = messageId;
            onRecordMessage({
                id: messageId,
                text: textBuffer.current,
                method: 'add',
            });
        }
        else {
            highlightText(textBuffer.messageId, textBuffer.current);
        }
    }, [onRecordMessage, highlightText]);
    const recProcess = useCallback((buffer, powerLevel, bufferDuration, bufferSampleRate) => {
        const data_48k = buffer[buffer.length - 1];
        const array_48k = new Array(data_48k);
        const data_16k = Recorder === null || Recorder === void 0 ? void 0 : Recorder.SampleData(array_48k, bufferSampleRate, 16000).data;
        if (!wsRef.current) {
            return;
        }
        if (wsRef.current.readyState !== WebSocket.OPEN) {
            return;
        }
        wsRef.current.send(Int16Array.from(data_16k));
        // 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);
        //   if (!wsRef.current) {
        //     return;
        //   }
        //   if (wsRef.current.readyState !== WebSocket.OPEN) {
        //     return;
        //   }
        //   wsRef.current.send(sendBuf);
        // }
    }, []);
    // 停止录音
    const stopRecord = useCallback(() => {
        var _a, _b;
        if (!recorderRef.current) {
            return;
        }
        recorderRef.current.close();
        if (((_a = wsRef.current) === null || _a === void 0 ? void 0 : _a.readyState) === WebSocket.OPEN && sampleBuf.length > 0) {
            wsRef.current.send(sampleBuf);
            sampleBuf = new Int16Array();
        }
        // wsRef.current.send(JSON.stringify(endWSParams));
        // 停止录音时，更新当前消息的文本
        if (fillMode === FILL_MODE.MESSAGE && textBuffer.current && textBuffer.messageId) {
            highlightText(textBuffer.messageId, textBuffer.current);
        }
        if (((_b = wsRef.current) === null || _b === void 0 ? void 0 : _b.readyState) === WebSocket.OPEN) {
            if (fillMode === FILL_MODE.INPUT) {
                wsRef.current.close();
                wsRef.current = null;
            }
            else {
                setTimeout(() => {
                    wsRef.current.close();
                    wsRef.current = null;
                }, 3000);
            }
        }
        stopTimer();
        setRecordStatus(RECORD_STATUS.DEFAULT);
        if (typeof onStopRecord === 'function') {
            onStopRecord();
        }
    }, [conversationId, stopTimer, highlightText, fillMode]);
    // 开始录音
    const startRecord = useCallback((options) => {
        const { conversationId: _conversationId = '', keywords: _keywords = [], fillMode: _fillMode = FILL_MODE.MESSAGE, minPowerLevel = 1, maxPowerLevel = 100, } = options;
        if (wsRef.current) {
            // 如果存在旧的WebSocket连接，先关闭它
            if (wsRef.current.readyState === WebSocket.CONNECTING) {
                wsRef.current.close();
            }
            wsRef.current = null;
        }
        // 初始化recorder实例
        if (!recorderRef.current) {
            recorderRef.current = Recorder({
                type: 'pcm',
                bitRate: 16,
                sampleRate: 16000,
                onProcess: (buffer, powerLevel, bufferDuration, bufferSampleRate) => {
                    if (powerLevel >= minPowerLevel && powerLevel <= maxPowerLevel) {
                        recProcess(buffer, powerLevel, bufferDuration, bufferSampleRate);
                    }
                },
                audioTrackSet: {
                    echoCancellation: true,
                    noiseSuppression: true,
                },
            });
        }
        // 开始录音，调用录音api
        recorderRef.current.open(() => {
            recorderRef.current.start();
        });
        // 创建 WebSocket 连接
        wsRef.current = new WebSocket(WEBSOCKET_URL); // 替换为你的 WebSocket URL
        wsRef.current.onclose = (event) => {
            if (!event.wasClean) {
                CnMessage.error($i18n.get({ id: 'AbnormalConnectionShutdown', dm: '连接异常关闭' }));
                console.error('websocket error closed', event);
                stopRecord();
            }
        };
        wsRef.current.onerror = (event) => {
            CnMessage.error($i18n.get({ id: 'ConnectionFailed', dm: '连接失败' }));
            console.error('websocket error', event);
            stopRecord();
        };
        // 处理消息
        wsRef.current.onmessage = (event) => {
            onSocketMessage(event, _fillMode);
        };
        wsRef.current.onopen = () => {
            const hotwords = {};
            _keywords.forEach((k) => {
                hotwords[`${k}`] = 10;
            });
        };
        setConversationId(_conversationId);
        setKeywords(_keywords);
        setFillMode(_fillMode);
        textBuffer.messageId = '';
        textBuffer.current = '';
        textBuffer.data = [];
        resetTimer();
        startTimer();
        setRecordStatus(RECORD_STATUS.RECORDING);
        if (typeof onStartRecord === 'function') {
            onStartRecord();
        }
    }, [recProcess, onSocketMessage, startTimer, resetTimer, onStartRecord, stopRecord]);
    // 继续录音
    const continueRecord = useCallback(() => {
        // 开始录音，调用录音api
        recorderRef.current.open(() => {
            recorderRef.current.start();
        });
        startTimer();
        setRecordStatus(RECORD_STATUS.RECORDING);
        if (typeof onContinueRecord === 'function') {
            onContinueRecord();
        }
    }, [startTimer, onContinueRecord]);
    // 暂停录音
    const pauseRecord = useCallback(() => {
        if (!recorderRef.current) {
            return;
        }
        recorderRef.current.close();
        stopTimer();
        setRecordStatus(RECORD_STATUS.PAUSED);
        if (typeof onPauseRecord === 'function') {
            onPauseRecord();
        }
    }, [stopTimer, onPauseRecord]);
    return {
        recordStatus,
        recordTime: formattedTime,
        startRecord,
        pauseRecord,
        continueRecord,
        stopRecord,
    };
}
