"use strict";

var mlink = require("../index");
var Router = mlink.Router;
var Logger = mlink.Logger;
var Hub = mlink.Hub;
var debuggerRouter = Router.get("debugger");
var DeviceManager = require("../managers/device_manager");
var RuntimeManager = require("../managers/runtime_manager");
var runtimeProxyHub = Hub.get("runtime.proxy");

debuggerRouter.registerHandler(function (message) {
  message.to("proxy.native");
}).at("sync.native");

debuggerRouter.registerHandler(function (message) {
  message.to("runtime.worker");
}).at("sync.v8");

debuggerRouter.registerHandler(function (message) {
  var payload = message.payload;
  if (payload.method === "syncReturn") {
    message.payload = {
      ret: payload.params.ret,
      id: payload.params.syncId
    };
    message.to("sync.v8");
  } else {
    message.to("proxy.native");
  }
}).at("runtime.worker");

debuggerRouter.on(Router.Event.TERMINAL_JOINED, "runtime.worker", function (signal) {
  RuntimeManager.connect(signal.channelId).then(function (terminal) {
    runtimeProxyHub.join(terminal);
    var device = DeviceManager.getDevice(signal.channelId);
    if (device) {
      if (device.remoteDebug === true) {
        debuggerRouter.pushMessageByChannelId("proxy.native", signal.channelId, {
          method: "WxDebug.reload"
        });
      }
    } else {
      Logger.error("device with channelId[" + signal.channelId + "] is not found");
    }
  }, function (errorText) {
    debuggerRouter.pushMessageByChannelId("page.debugger", signal.channelId, {
      method: "WxDebug.prompt",
      params: {
        messageText: errorText
      }
    });
  });
});

debuggerRouter.on(Router.Event.TERMINAL_LEAVED, "runtime.worker", function (signal) {
  if (RuntimeManager.has(signal.channelId)) {
    RuntimeManager.remove(signal.channelId);
  }
});