<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>webRTC</title>
</head>

<body>
    <div>
        <h1>webRTC</h1>
        <p>选择音乐使频道内所有设备同步播放 chrome://webrtc-internals/</p>
    </div>
    <script type="module">
        import IndexedDB from './database.js'
        import MusicList from './music.js'
        import ClientList from './client.js'

        // 缓冲分片发送
        const CHUNK_SIZE = 1024 * 64  // 默认每个块的大小为128KB
        const THRESHOLD = 1024 * 1024 // 默认缓冲区的阈值为1MB
        const DELAY = 50              // 默认延迟500ms

        // 将两个ArrayBuffer合并成一个
        function appendBuffer(buffer1, buffer2) {
            const tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength)
            tmp.set(new Uint8Array(buffer1), 0)
            tmp.set(new Uint8Array(buffer2), buffer1.byteLength)
            return tmp.buffer
        }

        // 读取本地音乐列表并标识为缓存状态(本地缓存)
        const database = new IndexedDB('musicDatabase', 1, 'musicObjectStore')
        await database.open()
        const list = (await database.getAll()).map(item => {
            return { save: true, ...item }
        })

        // 读取本地用户名(本地缓存)
        const name = localStorage.getItem('username') ?? '游客'

        // 初始化客户端列表
        const clientList = new ClientList({
            name,
            onexit: async client => {
                console.log(client.name, '离开频道', client)
                // 从列表中移除未缓存的此用户的音乐, 但可能多人都有此音乐且未缓存
                // 因此每条音乐都要检查是否有其他用户也有此音乐, 如果有则不移除
                const 此用户音乐 = client.musicList.map(item => item.id)
                const 无数据音乐 = musicList.list.filter(item => !item.arrayBuffer).filter(item => {
                    return 此用户音乐.includes(item.id)
                })
                无数据音乐.forEach(item => {
                    const client = clientList.clientlist.find(client => {
                        return client.musicList.find(x => x.id === item.id)
                    })
                    if (!client) musicList.remove(item)
                })

            }
        })

        // 初始化音乐列表(加入本地缓存)
        const musicList = new MusicList({
            list,
            onplay: item => {
                console.log('播放音乐', item.name)
            },
            onstop: item => {
                console.log('停止音乐', item?.name)
            },
            onlike: (item, list) => {
                console.log('喜欢音乐', item.name)
                if (item.arrayBuffer) {
                    database.add(item)
                    clientList.send('base', JSON.stringify({
                        type: 'set_music_list',
                        list: list.map(({ id, name, size, type }) => ({ id, name, size, type }))
                    }))
                }
            },
            onunlike: (item, list) => {
                console.log('取消喜欢', item.name)
                if (item.arrayBuffer) {
                    database.delete(item.id)
                    clientList.send('base', JSON.stringify({
                        type: 'set_music_list',
                        list: list.map(({ id, name, size, type }) => ({ id, name, size, type }))
                    }))
                }
            },
            onban: item => {
                console.log('禁止音乐', item.name)
            },
            onunban: item => {
                console.log('解禁音乐', item.name)
            },
            onremove: item => {
                console.log('移除音乐', item.name)
                database.delete(item.id)
            },
            onadd: (item, list) => {
                console.log('添加音乐', item.name)
            },
            onupdate: item => {
                console.log('更新音乐', item.name)
                database.put(item)
            },
            onerror: error => {
                console.log('音乐列表错误', error)
            },
            onload: async item => {
                console.log('加载音乐', item)
                return await new Promise((resolve) => {
                    var buffer = new ArrayBuffer(0) // 接收音乐数据
                    var count = 0                   // 接收分片计数
                    //var bufferCursor = 0            // 加载进度
                    //var partlength = 1024 * 64      // 每次加载1MB
                    //// 指针达到音乐数据大小则结束加载
                    //const mediaLoader = async () => {
                    //    while (bufferCursor !== item.size) {
                    //        if (musicList.audio.paused && musicList.audio.currentTime !== 0) {
                    //            console.log('音乐暂停')
                    //            break
                    //        }
                    //        console.log('当前播放进度', musicList.audio.currentTime)
                    //        const 当前播放进度 = musicList.audio.currentTime
                    //        const 当前结束时间 = sourceBuffer.buffered.length && sourceBuffer.buffered.end(0)
                    //        const 剩余数据长度 = buffer.byteLength - bufferCursor
                    //        const 本次加载长度 = Math.min(partlength, 剩余数据长度)
                    //        const 缓冲时间 = 当前结束时间 - 当前播放进度
                    //        if (buffer.byteLength > bufferCursor && !sourceBuffer.updating && 缓冲时间 < 60) {
                    //            sourceBuffer.appendBuffer(buffer.slice(bufferCursor, bufferCursor + 本次加载长度))
                    //            bufferCursor += 本次加载长度
                    //        }
                    //        await new Promise((resolve) => setTimeout(resolve, 1000))
                    //    }
                    //}
                    //mediaLoader()
                    clientList.setChannel(`music-data-${item.id}`, {
                        onmessage: async (event, client) => {
                            console.log('收到音乐数据 chunk', count, buffer.byteLength)
                            buffer = appendBuffer(buffer, event.data) // 合并分片准备存储
                            item.arrayBufferChunks.push(event.data)   // 保存分片给边下边播
                            count++
                            if (buffer.byteLength >= item.size) {
                                console.log('音乐数据接收完毕')
                                item.arrayBuffer = buffer
                                event.target.close() // 关闭信道
                                resolve(item)
                            }
                        }
                    })
                    const client = clientList.clientlist.find(client => {
                        return client.musicList.find(x => x.id === item.id)
                    })
                    console.log('向', client.name, '请求音乐数据')

                    const c = Math.ceil(item.size / CHUNK_SIZE)
                    console.log('需要接收', c, '个分片')

                    clientList.sendto(client.id, 'base', JSON.stringify({
                        type: 'get_music_data', id: item.id, channel: `music-data-${item.id}`
                    }))
                })
            }
        })

        // 只有一个基本信道, 用于交换和调度信息
        clientList.setChannel('base', {
            onopen: async event => {
                console.log('打开信道', event.target.label)
                // 要求对方发送音乐列表
                clientList.send('base', JSON.stringify({ type: 'get_music_list' }))
            },
            onmessage: async (event, client) => {
                const { type, id, channel, list } = JSON.parse(event.data)
                if (type === 'get_music_list') {
                    const ms = musicList.list.filter(item => item.arrayBuffer)
                    console.log(client.name, '请求音乐列表:', ms)
                    clientList.sendto(client.id, 'base', JSON.stringify({
                        type: 'set_music_list',
                        list: ms.map(({ id, name, size, type }) => ({ id, name, size, type }))
                    }))
                    return
                }
                if (type === 'set_music_list') {
                    console.log(client.name, '发来音乐列表:', `x${JSON.parse(event.data).list.length}`)
                    console.log('将列表保存到本机记录:', client)
                    client.musicList = list
                    client.musicList.forEach(music => musicList.add(music))
                    return
                }
                if (type === 'get_music_data') {
                    // 建立一个信道, 用于传输音乐数据(接收方已经准备好摘要信息)
                    console.log(client.name, '建立一个信道, 用于传输音乐数据', musicList.list)
                    musicList.list.filter(item => item.id === id).forEach(item => {
                        const ch = client.webrtc.createDataChannel(channel, { reliable: true })
                        ch.onopen = async event => {
                            console.log(client.name, `打开 ${channel} 信道传输音乐数据`, item.name)
                            // 将音乐数据分成多个小块,并逐个发送
                            async function sendChunk(dataChannel, data, index = 0, buffer = new ArrayBuffer(0)) {
                                while (index < data.byteLength) {
                                    if (dataChannel.bufferedAmount <= THRESHOLD) {
                                        const chunk = data.slice(index, index + CHUNK_SIZE)
                                        dataChannel.send(chunk)
                                        index += CHUNK_SIZE
                                        buffer = appendBuffer(buffer, chunk)
                                    }
                                    await new Promise((resolve) => setTimeout(resolve, DELAY))
                                }
                                return buffer
                            }
                            await sendChunk(ch, item.arrayBuffer)
                            console.log(client.name, `获取 ${channel} 信道数据结束`, item.name)
                            ch.close() // 关闭信道
                        }
                    })
                    return
                }
                console.log('未知类型:', type)
            },
            onclose: event => {
                console.log('关闭信道', event.target.label)
            },
            onerror: error => {
                console.log('信道错误', error)
            }
        })

        // 延迟1500ms
        //await new Promise((resolve) => setTimeout(resolve, 100))

        // 设置自己的主机名
        const nameInput = document.createElement('input')
        nameInput.type = 'text'
        nameInput.placeholder = '请设置你的名字'
        nameInput.value = name
        nameInput.onchange = event => {
            localStorage.setItem('username', event.target.value)
            window.location.reload() // 简单刷新页面
        }
        document.body.appendChild(nameInput)
    </script>
</body>

</html>