'use strict';

var _assign = require('babel-runtime/core-js/object/assign');

var _assign2 = _interopRequireDefault(_assign);

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

var os = require('os');
var mlink = require('../midware');
var debuggerRouter = mlink.Router.get('debugger');
var hook = require('../../util/hook');
var config = require('../../lib/config');
var DeviceManager = require('../managers/device_manager');
var redirectMessage = /^(Page.(enable|disable|reload)|Debugger|Target|Worker|Runtime\.runIfWaitingForDebugger)/;
var ignoredMessage = /^(ServiceWorker)/;

var _require = require('../../util/logger'),
    logger = _require.logger;

debuggerRouter.registerHandler(function (message) {
  var device = DeviceManager.getDevice(message.channelId);
  if (device) {
    if (redirectMessage.test(message.payload.method)) {
      if (message.payload && message.payload.method === 'Page.reload') {
        message.payload.ignoreCache = true;
      }
      message.to('runtime.proxy');
    } else if (ignoredMessage.test(message.payload.method)) {
      message.discard();
    } else {
      // remove useless but large message
      if (message.payload.method === 'Page.screencastFrameAck') {
        message.discard();
      } else {
        message.to('proxy.native');
      }
      if (message.payload.method === 'Page.startScreencast') {
        message.to('page.debugger');
      }
      if (message.payload.method === 'Runtime.enable') {
        message.payload.method = 'Console.enable';
        message.to('page.native');
      }
    }
    var params = (0, _assign2.default)({
      stack: 'ERROR: loss message from "proxy.inspector"',
      os: os.platform(),
      node: config.nodeVersion,
      npm: config.npmVersion
    }, config.weexVersion);
    hook.record('/weex_tool.weex_debugger.app_crash', params);
  } else {
    logger.error('loss message from "proxy.inspector" device not found in channelId [' + message.channelId + ']');
    message.to('proxy.native');
  }
}).at('proxy.inspector');