'user sctrict'


function devserverInit () {
    let reloadBlocksNoPlay = false
    const reloadTime = parseFloat(sessionStorage.getItem('reloadTime'))
    if (!Number.isNaN(reloadTime)) {
        transport.seekExact(parseFloat(reloadTime))
        const reloadPlayState = sessionStorage.getItem('reloadPlayState')
        if (reloadPlayState === 'true') {
            transport.setIsPlaying(true)
            reloadBlocksNoPlay = true
        }
    }
    sessionStorage.setItem('reloadTime', null)
    sessionStorage.setItem('reloadPlayState', null)

    console.log('Initialising devserver..')
    devserverState = 'open'
    devserverSocket = null
    devserverUpdate()

    return reloadBlocksNoPlay
}


let devserverState, devserverPinger, devserverSocket


function devserverUpdate () {
    switch (devserverState) {
        case 'open':
            devserverSocket = new WebSocket('ws://localhost:8086')
            devserverState = 'opening'
            devserverSocket.addEventListener('open', (e) => {
                console.log('Connected to devserver!')
                devserverState = 'opened'
            })
            devserverSocket.addEventListener('close', (e) => {
                if (devserverState === 'opened') {
                    console.log('Disconnected from devserver!')
                }
                devserverState = 'closed'
            })
            devserverSocket.addEventListener('error', (e) => {
                devserverState = 'closed'
            })
            devserverSocket.addEventListener('message', (e) => {
                const message = JSON.parse(e.data)
                if (message.type === 'reloadAll') {
                    console.log('[DEVSERVER] Hot reload all..')
                    sessionStorage.setItem('reloadTime', transport.getCurrentTime())
                    sessionStorage.setItem('reloadPlayState', transport.getIsPlaying())
                    window.location.reload()
                } else if (message.type === 'reloadScript') {
                    console.log('[DEVSERVER] Hot reload script..')
                    script = message.data
                    requestUpdate()
                } else if (message.type === 'loadModule') {
                    const moduleTitle = message.data.title
                    console.log(`[DEVSERVER] Hot reload module '${moduleTitle}'..`)
                    const savedModule = modules[moduleTitle]
                    try {
                        const module = Function(message.data.file)
                        module()
                        if (modules[moduleTitle].init) {
                            modules[moduleTitle].self = modules[moduleTitle].init()
                        } else {
                            modules[moduleTitle].self = {}
                        }
                        requestUpdate()
                    }
                    catch (e) {
                        console.log(`[DEVSERVER] Failed to reload -> ${e}`)
                        modules[moduleTitle] = savedModule
                    }
                } else {
                    console.log('[DEVSERVER] Unknown message from devServer:', message.type)
                }
            })
            break

        case 'opening':
        case 'opened':
            break
    
        case 'closed':
            devserverSocket.close()
            delete devserverSocket
            devserverState = 'open'
            break
    }

    setTimeout(devserverUpdate, 2000)
}
