'use strict';

var mlink = require('../midware');
var Router = mlink.Router;
var DeviceManager = require('../managers/device_manager');
var config = require('../../lib/config');
var debuggerRouter = Router.get('debugger');
var launcher = require('../../util/launcher');
var chalk = require('chalk');

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

var registerDeviceChannelId = void 0;
var FirstStartDebug = true;

debuggerRouter.on(Router.Event.TERMINAL_LEAVED, 'proxy.native', function (signal) {
  var device = DeviceManager.getDevice(signal.channelId);
  if (!device) {
    return;
  }
  // This is a special treatment for android devices
  // The android platform will registe twice and the socket leave signl may come after registed, the newly registered device may be removed immediately。
  if (device.platform === 'android' && FirstStartDebug) {
    FirstStartDebug = false;
  } else {
    DeviceManager.removeDevice(signal.channelId, function () {
      debuggerRouter.pushMessageByChannelId('page.debugger', signal.channelId, {
        method: 'AtomDebug.deviceDisconnect',
        params: device
      });
      debuggerRouter.pushMessageByChannelId('runtime.worker', signal.channelId, {
        method: 'AtomDebug.deviceDisconnect',
        params: device
      });
    });
  }
});

debuggerRouter.on(Router.Event.TERMINAL_JOINED, 'page.debugger', function (signal) {
  var device = DeviceManager.getDevice(signal.channelId);
  // Fixme Android will connect twice while first scan.
  if (registerDeviceChannelId === signal.channelId) {
    FirstStartDebug = true;
  }
  registerDeviceChannelId = signal.channelId;
  debuggerRouter.pushMessageByChannelId('page.debugger', signal.channelId, {
    method: 'AtomDebug.pushDebuggerInfo',
    params: {
      device: device,
      bundles: config.bundleUrls,
      connectUrl: config.getConnectUrl(signal.channelId)
    }
  });
});

debuggerRouter.registerHandler(function (message) {
  var device = DeviceManager.registerDevice(message.payload.params, message.channelId);
  if (device) {
    message.payload = {
      method: 'AtomDebug.pushDebuggerInfo',
      params: {
        device: device,
        bundles: config.bundleUrls,
        connectUrl: config.getConnectUrl(message.channelId)
      }
    };
    debuggerRouter.pushMessage('page.entry', {
      method: 'AtomDebug.startDebugger',
      params: message.channelId
    });
    var msg = chalk.bold('Debug Url:    ') + config.getDebugUrl(message.channelId);
    logger.log(msg);
    launcher.launchChrome(config.getDebugUrl(message.channelId), config.remoteDebugPort || 9222);
    message.to('page.debugger');
  }
  return false;
}).at('proxy.native').when('payload.method=="AtomDebug.registerDevice"');