/**
 * @file runtime
 *
 * @author atome-engine
 */
let worker;
let RuntimeSocket;
let BrowserChannelId;

 /*eslint-disable*/
BrowserChannelId = new URLSearchParams(location.search).get('channelId');
if (BrowserChannelId) {
    connect(BrowserChannelId);
} else {
    let EntrySocket = new WebsocketClient('ws://' + location.host + '/page/entry');
    EntrySocket.on('AtomDebug.startDebugger', function (message) {
        console.error('start debug');
        if (!RuntimeSocket) {
            // location.href = `http://${location.host}/runtime.html?channelId=${message.params}`
            window.open(`http://${location.host}/runtime.html?channelId=${message.params}`);
        } else if (RuntimeSocket && BrowserChannelId !== message.params) {
            // location.href = `http://${location.host}/runtime.html?channelId=${message.params}`
            window.open(`http://${location.host}/runtime.html?channelId=${message.params}`);
        }
    })
}

function connect(channelId) {
    RuntimeSocket = new WebsocketClient('ws://' + window.location.host + '/debugProxy/runtime/' + channelId);
    RuntimeSocket.on('*', function (message) {
        // throw new Error(message);
        if (worker) {
            worker.postMessage(message);
        }
    });
    RuntimeSocket.on('AtomDebug.deviceDisconnect', function () {
        window.close();
        // location.href = `http://${location.host}/runtime.html`
    });
    RuntimeSocket.on('AtomDebug.refresh', function () {
        location.reload();
    });
    RuntimeSocket.on('AtomDebug.initJSRuntime', function (message) {
        destroyJSRuntime();
        let logLevel = localStorage.getItem('logLevel');
        if (logLevel) {
            message.params.env.WXEnvironment.logLevel = logLevel;
        }
        message.channelId = BrowserChannelId;
        initJSRuntime(message);
    });
    RuntimeSocket.on('AtomDebug.setFrameworkLog', function (message) {
        if (!worker) {
            worker = new Worker('/lib/runtime/Runtime.js');
        }
        worker.postMessage(message);
    });
}

function destroyJSRuntime() {
    if (worker) {
        worker.terminate();
        worker.onmessage = null;
        worker = null;
    }
}

function initJSRuntime(message) {
    worker = new Worker('/lib/runtime/Runtime.js');
    worker.onmessage = function (message) {
        message = message.data;
        RuntimeSocket.send(message);
        let domain = message.method.split('.')[0];
        let method = message.method.split('.')[1];
        if (domain == 'Runtime') {
            if (method === 'clearLog') {
                // console.clear();
            } else if (method === 'dom') {
                document.getElementById('dom').innerHTML = resolve(message.params);
            }
        }
    };
    worker.postMessage(message);
}
//initJSRuntime();
function resolve(root) {
    let html = `<${root.type} ${resolveStyle(root.style)}`;
    let value = '';
    for (let key in root.attr) {
        if (root.attr.hasOwnProperty(key)) {
            if (root.type == 'text' && key == 'value') {
                value = root.attr[key];
            }
            html += ` ${key}="${root.attr[key]}"`;
        }
    }
    html += '>';
    if (value) {
        html += value;
    } else {
        for (let i = 0; root.children && i < root.children.length; i++) {
            html += resolve(root.children[i]);
        }
    }
    html += `</${root.type}>`;
    return html;
}

function resolveStyle(styles) {
    let styleText = '';
    for (let key in styles) {
        if (styles.hasOwnProperty(key)) {
            styleText += key.replace(/([a-z])([A-Z])/g, function (m, a, b) {
                return a + '-' + b.toLowerCase();
            }) + ':' + resolveStyleValue(styles[key]) + ';';
        }
    }
    if (styleText) {
        styleText = ` style="${styleText}"`;
    }
    return styleText;
}
let cssNumber = {
    columnCount: true,
    fillOpacity: true,
    flexGrow: true,
    flexShrink: true,
    fontWeight: true,
    lineHeight: true,
    opacity: true,
    order: true,
    orphans: true,
    widows: true,
    zIndex: true,
    zoom: true
};

function resolveStyleValue(value) {
    if (isNaN(value) || cssNumber[value]) {
        return value;
    } else {
        return value + 'px';
    }
}
/*eslint-enable*/