// composables/useTeardown.js

export function useTeardown(deps) {
    let sseRef = null;
    let multiplexWS = null;

    function setSSE(es) {
        try { sseRef?.close?.(); } catch { }
        sseRef = es;
    }

    function setMultiplexWS(ws) {
        try { multiplexWS?.close?.(); } catch { }
        multiplexWS = ws;
    }

    function disposeDevice(index) {
        try {
            const di = deps.deviceInformation.value[index];
            const udid = di?.udid;

            // 停止定时器
            if (deps.playTimer.value[index]) {
                clearTimeout(deps.playTimer.value[index]);
                deps.playTimer.value[index] = null;
            }
            const inst = deps.instanceList[index];
            if (inst?.timer) {
                clearInterval(inst.timer);
                inst.timer = null;
            }

            // 关闭 WS
            const ws = deps.wslist[index];
            if (ws) {
                ws.onopen = ws.onmessage = ws.onerror = ws.onclose = null;
                try { ws.close(); } catch { }
                deps.wslist[index] = undefined;
            }
            if (udid) deps.wsCache.delete(udid);

            // 销毁解码器
            try {
                inst?.converter?.destroy?.();
            } catch { }
            if (deps.instanceList[index]) deps.instanceList[index].converter = undefined;

            // 释放 <video>
            if (udid) {
                const video = deps.videoElement.value?.[udid];
                if (video) {
                    try { video.pause?.(); } catch { }
                    try { video.removeAttribute?.('src'); } catch { }
                    try { video.load?.(); } catch { }
                    delete deps.videoElement.value[udid];
                }
                if (deps.canvasRef.value?.[udid]) {
                    delete deps.canvasRef.value[udid];
                }
            }

            // 清空任务队列
            try { deps.createTaskQueue(index).clear(); } catch { }

        } catch (e) {
            console.error('[disposeDevice] error:', index, e);
        }
    }

    function disposeAll(reason = 'manual') {
        console.log('[teardown] disposeAll:', reason);

        // 停止全局监控
        try { deps.stopAll?.(); } catch { }

        // 释放所有设备
        const n = deps.deviceInformation.value.length;
        for (let i = 0; i < n; i++) disposeDevice(i);
        deps.deviceInformation.value = [];

        // 关闭 multiplex WS
        try { multiplexWS?.close?.(); } catch { }
        multiplexWS = null;

        // 关闭 SSE
        try { sseRef?.close?.(); } catch { }
        sseRef = null;

        // 页级定时器
        if (deps.isShowMes.value) {
            clearInterval(deps.isShowMes.value);
            deps.isShowMes.value = undefined;
        }

        // 清空缓存
        deps.wsCache.clear?.();

        // 全局事件监听
        try { deps.removeDocListeners?.(); } catch { }
    }

    return {
        setSSE,
        setMultiplexWS,
        disposeDevice,
        disposeAll,
    };
}
