/*eslint-disable*/
const channelId = new URLSearchParams(location.search).get('channelId');
let screencastParams = null;
const $tipsMask = $('.tips-mask');
const $inspectorPage = $('#inspector');
const $debuggerMenu = $('#debugger-menu');
const $remoteDebug = $('#remote_debug');
let hash = window.location.hash || '#debugger';
const shouldShowStepTips = localStorage.getItem('shouldShowStepTips')
let timeout;

websocket = new WebsocketClient('ws://' + location.host + '/debugProxy/debugger/' + channelId);
websocket.on('socketOpened', () => {
    let toDebuggerPage = function () {
        $debuggerMenu.style.display = 'block';
        $inspectorPage.style.display = 'block';
        websocket.send({
            method: 'AtomDebug.enableTracing',
            params: {
                status: false
            }
        });
        if (screencastParams) {
            websocket.send({
                method: 'Page.startScreencast',
                params: screencastParams
            });
        }
    }
    if (hash === '#debugger') {
        toDebuggerPage();
    }
    window.addEventListener('hashchange', function (e) {
        hash = new URL(e.newURL).hash;
        if (hash === '#debugger') {
            toDebuggerPage();
        }
    }, false);
})
websocket.ws.onclose = function () {
    history.back()
}
websocket.on('AtomDebug.pushDebuggerInfo', function (event) {
    let remoteTimer;
    let networkTimer;
    clearTimeout(timeout)
    if (event.params) {
        let device = event.params.device
        let name = device.name
        if (name && name.indexOf('com.') === 0) {
            let split = name.split('.')
            name = split.slice(Math.min(split.length - 1, 2)).join('.')
        }
        if (device.pageId) {
            document.title = 'Page - ' + device.pageId
        } else {
            document.title = 'Atom Debugger'
        }
        let appInfo = name + '@' + device.model
        let sdkVersion = 'v ' + device.atomVersion + ' - ' + device.platform + ' (inspector ' + device.devtoolVersion + ')'
        $('#app_info').innerHTML = appInfo
        $('#app_info').title = device.name + '@' + device.model
        $('#sdk_version').innerHTML = sdkVersion
        $('#remote_debug').checked = typeof (device.remoteDebug) === "undefined" ? false : device.remoteDebug;
        $('#network').checked = typeof (device.network) === "undefined" ? false : device.network;
        $('#element_mode').value = device.elementMode || sessionStorage.getItem('elmentMode') || 'native'
        $('#log_level').value = sessionStorage.getItem('logLevel') || 'debug';
        $('#commands').checked = localStorage.getItem('commandsLog') === 'true';
        $('#framework').checked = localStorage.getItem('frameworkLog') === 'true';
        $('#debuggerInteract').checked = localStorage.getItem('debuggerInteract') === 'true';
        $('#remote_debug').onchange = function () {
            let checked = this.checked;
            remoteTimer && clearTimeout(remoteTimer)
            remoteTimer = setTimeout(function () {
                websocket.send({
                    method: 'AtomDebug.' + (checked ? 'enable' : 'disable')
                })
            }, 200)
        }
        $('#network').onchange = function () {
            let checked = this.checked;
            networkTimer && clearTimeout(networkTimer)
            networkTimer = setTimeout(function () {
                websocket.send({
                    method: 'AtomDebug.network',
                    params: {
                        enable: checked
                    }
                })
            }, 200)
        }
        $('#element_mode').onchange = function () {
            localStorage.setItem('elmentMode', this.value);
            websocket.send({
                method: 'AtomDebug.setElementMode',
                params: {
                    data: this.value
                }
            })
        }
        $('#log_level').onchange = function () {
            localStorage.setItem('logLevel', this.value);
            websocket.send({
                method: 'AtomDebug.setLogLevel',
                params: {
                    data: this.value
                }
            })
        }

        // add by wangjie23
        $('#commands').onchange = function () {
            localStorage.setItem('commandsLog', this.checked);
            /*eslint-disable*/
            websocket.send({
                method: 'AtomDebug.setCommandsLog',
                params: {
                    data: this.checked
                }
            });
            /*eslint-disable*/
        };

        $('#framework').onchange = function () {
            localStorage.setItem('frameworkLog', this.checked);
            /*eslint-disable*/
            websocket.send({
                method: 'AtomDebug.setFrameworkLog',
                params: {
                    data: this.checked
                }
            });
            /*eslint-disable*/
        };

        $('#debuggerInteract').onchange = function () {
            localStorage.setItem('debuggerInteract', this.checked);
            /*eslint-disable*/
            websocket.send({
                method: 'AtomDebug.setDebuggerInteract',
                params: {
                    data: this.checked
                }
            });
            /*eslint-disable*/
        };

        initDevtoolIframe();
    }
})
websocket.on('AtomDebug.prompt', function (event) {
    let delayed = 5000 + event.params.messageText.length / 6 * 1000
    toast(translateI18n(event.params.messageText).replace(/\n/g, '<br>'), delayed)
})

websocket.on('AtomDebug.reloadInspector', function (event) {
    $('#inspector').contentWindow.location.reload();
})
websocket.on('AtomDebug.deviceDisconnect', function (event) {
    timeout = setTimeout(function () {
        window.close();
    }, 0);
})
websocket.on('AtomDebug.bundleRendered', function (event) {
    // refresh的时候更新设置
    setCustomLog();
    let found = false
    if (!event.params) found = true
    else {
        window._bundles && window._bundles.forEach(function (url) {
            if (url === event.params.bundleUrl) {
                found = true
            }
        })
    }
    if (found) {
        $('.bundle-qrcode').style.display = 'none'
    }
})
websocket.on('Page.startScreencast', function (event) {
    screencastParams = event.params;
})

// 设置自定义的日志展现
function setCustomLog() {
    // 初始化值状态
    if (localStorage.getItem('commandsLog') === 'true') {
        /*eslint-disable*/
        websocket.send({
            method: 'AtomDebug.setCommandsLog',
            params: {
                data: true
            }
        });
        /*eslint-disable*/
    }

    if (localStorage.getItem('frameworkLog') === 'true') {
        /*eslint-disable*/
        websocket.send({
            method: 'AtomDebug.setFrameworkLog',
            params: {
                data: {
                    messageText: true
                }
            }
        });
        /*eslint-disable*/
    }

    if (localStorage.getItem('commandsLog') === 'true') {
        /*eslint-disable*/
        websocket.send({
            method: 'AtomDebug.setDebuggerInteract',
            params: {
                data: {
                    status: true
                }
            }
        });
        /*eslint-disable*/
    }
}

function initDevtoolIframe() {
    $('#inspector').src = `/inspector/inspector.html?ws=${location.host}/debugProxy/inspector/${channelId}&remoteFrontend=1`
    let shouldReloadApp = true
    $('#inspector').onload = function () {
        if (!shouldReloadApp && $('#remote_debug').checked) {
            websocket.send({
                method: 'AtomDebug.reload'
            })
        }
        shouldReloadApp = false
        $('#inspector').contentDocument.addEventListener('keydown', function (evt) {
            if (evt.key == 'r' && (evt.metaKey || evt.altKey) || evt.key == 'F5') {
                evt.preventDefault()
                evt.stopPropagation()
                websocket.send({
                    method: 'AtomDebug.refresh'
                })
                return false
            }
        }, true)
        setCustomLog();
    }
}

// function initTips() {
//     new AnchorTips(document.querySelectorAll('.line.short>span:nth-child(1)')[0], AnchorTips.LEFT, generatei18nTips('JSDEBUG_TIP'), $('.tips-mask'))
//     new AnchorTips(document.querySelectorAll('.line.short>span:nth-child(1)')[1], AnchorTips.LEFT_BOTTOM, generatei18nTips('NETWORK_TIP'), $('.tips-mask'))
//     new AnchorTips(document.querySelectorAll('.line.middle>span:nth-child(1)')[0], AnchorTips.RIGHT, generatei18nTips('LOGLEVEL_TIP'), $('.tips-mask'))
//     new AnchorTips(document.querySelectorAll('.line.middle>span:nth-child(1)')[1], AnchorTips.RIGHT_BOTTOM, generatei18nTips('ELEMENT_MODE_TIP'), $('.tips-mask'))
// }

function init() {
    document.onkeydown = function (evt) {
        if (evt.key == 'r' && (evt.metaKey || evt.altKey) || evt.key == 'F5') {
            evt.preventDefault();
            return false
        }
        else if (evt.key == 'n' && evt.ctrlKey) {
            evt.preventDefault();
            window.open('/#new', '_blank')
            return false
        }
    }
    document.addEventListener('click', function (e) {
        let target = e.target;
        if (hasClassName(target, 'icon-bangzhu')) {
            replaceClassName('.help span', 'icon-bangzhu', 'icon-close')
            $tipsMask.style.display = 'block'
            setTimeout(function () {
                $tipsMask.className += ' widget-anchor-show'
            }, 100)
        }
        else if (hasClassName(target, 'icon-close')) {
            replaceClassName('.help span', 'icon-close', 'icon-bangzhu')
            $tipsMask.className = $tipsMask.className.replace(/ widget-anchor-show/g, '')
            setTimeout(function () {
                $tipsMask.style.display = 'none'
            }, 400)
        }
        else if (hasClassName(target, 'refresh-btn')) {
            websocket.send({
                method: 'AtomDebug.reload'
            });
        }
    })
    if (shouldShowStepTips) {
        $('.help').click()
        localStorage.setItem('shouldShowStepTips', false)
    }
    // initTips();
}
init();
/*eslint-enable*/