'use strict';

var mlink = require('../midware');
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');
debuggerRouter.registerHandler(function (message) {
  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: 'AtomDebug.reload'
        });
      }
    } else {
      Logger.error('device with channelId[' + signal.channelId + '] is not found');
    }
  }, function (errorText) {
    debuggerRouter.pushMessageByChannelId('page.debugger', signal.channelId, {
      method: 'AtomDebug.prompt',
      params: {
        messageText: errorText
      }
    });
  });
});

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