// src/composables/useDeviceDiscovery.js  
import { nextTick } from 'vue'

/**
 * 负责连接 multiplex WebSocket，维护 deviceInformation 列表，
 * 并在设备出现时按顺序调用 initCanvas / initVideoStream / getSize。
 * 获取设备的ws
 */
export function useDeviceDiscovery({
    deviceInformation,   // ref([])
    initCanvas,          // (udid) => void
    initVideoStream,     // (udid, index) => void
    wsActionsRef,        // () => wsActions (可能一开始是 null)
    td                   // 你的 useTeardown 实例，可选
}) {
    const decoder = new TextDecoder('utf-8')

    function open(url, eitwoBuffer) {
        const ws = new WebSocket(url)
        td && td.setMultiplexWS && td.setMultiplexWS(ws) // 交给 teardown 托管
        ws.binaryType = 'arraybuffer'

        ws.onopen = () => {
            ws.send(eitwoBuffer) // 请求设备列表
        }

        ws.onmessage = async (event) => {
            let data
            try {
                // 兼容原逻辑：先解码再清理不可见字符再 JSON 解析
                data = JSON.parse(decoder.decode(event.data).replace(/[^\x20-\x7F]/g, ''))
            } catch (e) {
                console.error('[multiplex] parse error:', e)
                return
            }

            if (data.type === 'devicelist') {
                // 全量刷新
                deviceInformation.value = []
                const list = (data.data.list || []).filter(it => it.state === 'device')

                for (let i = 0; i < list.length; i++) {
                    const item = list[i]
                    deviceInformation.value.push(item)

                    await nextTick()           // 等 v-for 渲染出 <video>
                    initCanvas(item.udid)
                    initVideoStream(item.udid, i)

                    // 延迟拉尺寸（和你原逻辑一致）
                    setTimeout(() => {
                        const wsActions = wsActionsRef && wsActionsRef()
                        wsActions && wsActions.getSize && wsActions.getSize(item.udid, i)
                    }, 2000)
                }
            }

            else if (data.type === 'device') {
                const d = data.data.device

                if (d.state === 'offline') {
                    // 移除离线设备
                    const idx = deviceInformation.value.findIndex(x => x.udid === d.udid)
                    if (idx !== -1) {
                        deviceInformation.value.splice(idx, 1)
                    }
                }

                else if (d.state === 'device') {
                    // 新设备上线
                    const exists = deviceInformation.value.some(x => x.udid === d.udid)
                    if (!exists) {
                        deviceInformation.value.push(d)
                        // 稍等一会再初始化，保持与原代码行为一致
                        setTimeout(async () => {
                            try {
                                const i = deviceInformation.value.length - 1
                                await nextTick()
                                initCanvas(d.udid)
                                initVideoStream(d.udid, i)
                            } catch (e) {
                                console.warn('[multiplex] online init failed:', e)
                            }
                        }, 1000)
                    }
                }
            }
        }

        ws.onerror = (e) => {
            console.error('[multiplex] ws error:', e)
        }

        ws.onclose = () => {
            // 可按需在这里做重连；现在保持与原逻辑一致不做自动重连
        }

        return ws
    }

    return { open }
}
