/**
 * Module dependencies.
 */

var package = require(__dirname+'/package.json');
var config = require(package.path.config);
var express = require('express');
var routes = require(__dirname+'/routes');
var app = module.exports = express.createServer();
var io  = require('socket.io').listen(app);
var sql = require(__dirname+'/database')(config.mysql);
var sockets = require(__dirname+'/sockets')(sql);

// Configuration
process.argv.forEach(function(val, index) {
  if (index<2) {return}
  if (index!=2 || isNaN(val)) {
    console.log("**** ERROR: Unexpected Argument - allowed is only a port number");
    process.exit(1);
  }
  config.port = parseInt(val);
});
if (typeof config.port != 'number') {
  console.log("**** WARNING: no valid port given, defaults to 8888");
  config.port = 8888;
}

app.configure(function() {
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(require('stylus').middleware({ src: __dirname + '/public' }));
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
  [
    'jquery/dist',
    'openpgp/dist'
  ].forEach(function(file) {
    app.use('/'+file.replace(/\/.*/g, ''),
            express.static(__dirname + '/node_modules/'+file));
  })
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

// Sockets

io.sockets.on('connection', sockets.connection);

// Routes

app.get('/', routes.index);
app.get('/webrtc', routes.webrtc);

app.listen(config.port, function(){
  console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
});
