'use strict';

var _slicedToArray2 = require('babel-runtime/helpers/slicedToArray');

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _regenerator = require('babel-runtime/regenerator');

var _regenerator2 = _interopRequireDefault(_regenerator);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * Created by godsong on 16/6/13.
 */
var Router = require('koa-router');
var P2PSession = require('../components/P2PSession');
var DeviceManager = require('../components/DeviceManager');
var MemoryFile = require('../components/MemoryFile');
var uuid = require('../util/uuid');
var Logger = require('../components/Logger');
var Config = require('../components/Config');
var wsRouter = Router();
var bundleWrapper = 'function __weex_bundle_entry__(define, require, document, bootstrap,register, render, __weex_define__, __weex_bootstrap__){';
var chromeWsIndex = 2;
var nativeWsIndex = 1;
function _toFixed(num) {
    var s = num.toString(16);
    if (s.length % 2 == 1) {
        return '0' + s;
    } else return s;
}
wsRouter.all('/debugProxy/inspector/:sessionId', _regenerator2.default.mark(function _callee(next) {
    return _regenerator2.default.wrap(function _callee$(_context) {
        while (1) {
            switch (_context.prev = _context.next) {
                case 0:
                    Logger.log('new inspector client connected,join[' + this.params.sessionId + ']');
                    this.websocket._info = 'chrome-inspector[' + this.params.sessionId + '0x' + _toFixed(chromeWsIndex++) + ']';
                    if (P2PSession.join(this.params.sessionId, this.websocket)) ;
                    this.websocket.on('message', function (message) {
                        message = JSON.parse(message);
                        P2PSession.postMessage(this, message);
                    });
                    _context.next = 6;
                    return next;

                case 6:
                case 'end':
                    return _context.stop();
            }
        }
    }, _callee, this);
}));
wsRouter.all('/debugProxy/debugger/:sessionId', _regenerator2.default.mark(function _callee2(next) {
    return _regenerator2.default.wrap(function _callee2$(_context2) {
        while (1) {
            switch (_context2.prev = _context2.next) {
                case 0:
                    Logger.log('new debugger client connected,join[' + this.params.sessionId + ']');
                    this.websocket._info = 'chrome-debugger[' + this.params.sessionId + '0x' + _toFixed(chromeWsIndex++) + ']';
                    if (!P2PSession.join(this.params.sessionId, this.websocket)) {
                        P2PSession.postMessage(this.websocket, { method: "WxDebug.reload" });
                    }
                    this.websocket.on('message', function (message) {
                        message = JSON.parse(message);
                        Logger.printMessage(message, 'chrome');
                        P2PSession.postMessage(this, message);
                    });
                    _context2.next = 6;
                    return next;

                case 6:
                case 'end':
                    return _context2.stop();
            }
        }
    }, _callee2, this);
}));
DeviceManager.on('update', function (deviceList) {
    listPageWebsocket.forEach(function (ws) {
        ws.send(JSON.stringify({ method: "WxDebug.pushDeviceList", params: deviceList }));
    });
});
var listPageWebsocket = [];
wsRouter.all('/debugProxy/list', _regenerator2.default.mark(function _callee3(next) {
    return _regenerator2.default.wrap(function _callee3$(_context3) {
        while (1) {
            switch (_context3.prev = _context3.next) {
                case 0:
                    listPageWebsocket.push(this.websocket);
                    this.websocket.on('close', function () {
                        var _this = this;

                        listPageWebsocket = listPageWebsocket.filter(function (ws) {
                            return ws !== _this;
                        });
                    });
                    this.websocket.send(JSON.stringify({ method: "WxDebug.pushDeviceList", params: DeviceManager.getDeviceList() }));
                    if (Config.entryBundleUrl) this.websocket.send(JSON.stringify({ method: "WxDebug.setEntry", params: Config.entryBundleUrl }));

                case 4:
                case 'end':
                    return _context3.stop();
            }
        }
    }, _callee3, this);
}));

wsRouter.all('/debugProxy/native', _regenerator2.default.mark(function _callee4(next) {
    return _regenerator2.default.wrap(function _callee4$(_context4) {
        while (1) {
            switch (_context4.prev = _context4.next) {
                case 0:
                    Logger.log('new native  client connected');
                    this.websocket._info = nativeWsIndex.toString(16) + ' unregistered';
                    nativeWsIndex++;
                    this.websocket.on('message', function (messageText) {
                        var message = JSON.parse(messageText);
                        Logger.printMessage(message, 'native');
                        var device = DeviceManager.getDevice(this);
                        if (message.method) {
                            var _message$method$split = message.method.split('.');

                            var _message$method$split2 = (0, _slicedToArray3.default)(_message$method$split, 2);

                            var domain = _message$method$split2[0];
                            var method = _message$method$split2[1];

                            if (domain == 'WxDebug') {
                                if (method == 'registerDevice') {
                                    DeviceManager.registerDevice(message.params, this);
                                    this.send(JSON.stringify({ id: message.id, result: 'ready' }));
                                } else if (method == 'initJSRuntime') {
                                    message.params.url = new MemoryFile('js-framework.js', message.params.source).getUrl();
                                    device.debuggerSession.postMessage(this, message);
                                } else if (method == 'callJS' && message.params.method == 'createInstance') {
                                    message.params.sourceUrl = new MemoryFile(message.params.args[2].bundleUrl || uuid() + '.js', bundleWrapper + message.params.args[1] + '\n}').getUrl();
                                    device.debuggerSession.postMessage(this, message);
                                } else {
                                    if (device) device.debuggerSession.postMessage(this, message);else Logger.error('undefined device');
                                }
                            } else {
                                if (device) device.inspectorSession.postMessage(this, message);else Logger.error('undefined device');
                            }
                        } else {
                            if (device) device.inspectorSession.postMessage(this, message);else Logger.error('undefined device');
                        }
                    });
                    this.websocket.on('close', function () {
                        var device = DeviceManager.getDevice(this);
                        DeviceManager.removeDeviceDelayed(device, 3000);
                    });
                    _context4.next = 7;
                    return next;

                case 7:
                case 'end':
                    return _context4.stop();
            }
        }
    }, _callee4, this);
}));
module.exports = wsRouter;