"use strict";

var mlink = require("../index");
var Router = mlink.Router;
var DeviceManager = require("../managers/device_manager");
var config = require("../../config");

var _require = require("../../util"),
    util = _require.util;

var debuggerRouter = Router.get("debugger");

debuggerRouter.on(Router.Event.TERMINAL_LEAVED, "proxy.native", function (signal) {
  var device = DeviceManager.getDevice(signal.channelId);
  if (!device) {
    return;
  }
  DeviceManager.removeDevice(signal.channelId, function () {
    debuggerRouter.pushMessageByChannelId("page.debugger", signal.channelId, {
      method: "WxDebug.deviceDisconnect",
      params: device
    });
  });
});

debuggerRouter.on(Router.Event.TERMINAL_JOINED, "page.debugger", function (signal) {
  var device = DeviceManager.getDevice(signal.channelId);
  debuggerRouter.pushMessageByChannelId("page.debugger", signal.channelId, {
    method: "WxDebug.pushDebuggerInfo",
    params: {
      device: device,
      bundles: config.BUNDLE_URLS || [],
      connectUrl: util.getConnectUrl(signal.channelId)
    }
  });
});

debuggerRouter.registerHandler(function (message) {
  var device = DeviceManager.registerDevice(message.payload.params, message.channelId);
  if (device) {
    message.payload = {
      method: "WxDebug.pushDebuggerInfo",
      params: {
        device: device,
        bundles: config.BUNDLE_URLS || [],
        connectUrl: util.getConnectUrl(message.channelId)
      }
    };
    debuggerRouter.pushMessage("page.entry", {
      method: "WxDebug.startDebugger",
      params: message.channelId
    });
    message.to("page.debugger");
  }
  return false;
}).at("proxy.native").when('payload.method=="WxDebug.registerDevice"');