'use strict';

var path = require('path');
var fs = require('fs');
var koa = require('koa');
var serve = require('koa-serve');
var serveStatic = require('koa-serve-static');
var websockify = require('koa-websocket');
var app = websockify(koa());
var wsRouter = require('./router/websocket');
var httpRouter = require('./router/http');
var rootpath = path.join(__dirname, '../frontend/');
var getIP = require('./util/getIP');
var launchDevTool = require('./util/launchDevTool');

/* 
 ===================================
 WebSocket Router
 ===================================
 */
module.exports = function (port) {

    app.ws.use(wsRouter.routes());
    app.on('error', function (err, ctx) {
        console.error(err.message);
    });
    /*
     ===================================
     Http Router
     ===================================
     */

    app.use(httpRouter.routes());
    app.use(serveStatic(rootpath));

    app.listen(port);
    getIP(function (err, ips) {
        console.info('start debugger server at http://' + ips[0] + ':' + port);
        console.info('the websocket address for native is ws://' + ips[0] + ':' + port + '/debugProxy/native');
        launchDevTool(ips[0], port);
    });
};