'use strict';

var path = require('path');
var Koa = require('koa');
var serve = require('koa-serve-static');
var Websockify = require('koa-websocket');
var bodyParser = require('koa-bodyparser');
var WsRouter = require('./router/Websocket');
var HttpRouter = require('./router/Http');
var app = Websockify(new Koa());
var rootPath = path.join(__dirname, '../../frontend/');

var _require = require('../mlink/link'),
    init = _require.init;

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

/*
 ===================================
 WebSocket Router
 ===================================
 */

exports.start = function (port, cb) {
  // mlink 初始化debuggerRouter
  init();
  // start koa server
  app.use(bodyParser());
  app.ws.use(WsRouter.routes());
  app.on('error', function (err, ctx) {
    if (err.status === 404) {
      logger.verbose(err);
    } else {
      logger.verbose(err);
    }
  });
  /*
   ===================================
   Http Router
   ===================================
   */
  app.use(HttpRouter.routes());
  app.use(serve(rootPath));

  app.listen(port, cb);
};