#!/usr/bin/env node
/*
 * Copyright (C) 2015 Centro de Computacao Cientifica e Software Livre
 * Departamento de Informatica - Universidade Federal do Parana
 *
 * This file is part of simmc.
 *
 * simmc is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * simmc is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with simmc.  If not, see <http://www.gnu.org/licenses/>.
 */

// Add the ./lib directory to require's search path to facilitate requiring
// libraries later on (avoiding the require('../../../../library.js') problem).
require('app-module-path').addPath(__dirname + '/lib');

// external libraries
var osprey = require('osprey');
var express = require('express');
var path = require('path');
var ramlParser = require('raml-parser');

// internal libraries (from ./lib)
var configParser = require('config-parser');
var errorHandler = require('error-handler');
var logger = require('logger');

var app = module.exports = express();

// parse and load configuration
var config = configParser.readFromFile(
        path.resolve(__dirname, './config/' + app.get('env') + '.yaml'));
app.set('port', process.env.PORT || config.get('port') || 3000);

// add an access logger middleware
app.use(logger.accessLogger(app.get('env')));

// include middlewares
app.use(require('./api/middleware/mongodb.js')(config));

// load router
var router = require('./api/router-v1.js');

// parse the RAML spec and load osprey middleware
ramlParser.loadFile(path.join(__dirname, 'api/specs/simmc-api-v1.raml'))
    .then(function(raml) {
        app.use('/api/v1',
            osprey.security(raml),
            osprey.server(raml),
            router,
            errorHandler);

        if (!module.parent) {
            var port = app.get('port');
            app.listen(port);

            if (app.get('env') === 'development') {
                logger.info('Server listening on port ' + port + '.');
            }
        }
        else {
            // signalize to the test suite that the server is ready to be tested
            app.ready = true;
        }
    },
    function(err) {
        logger.error('RAML Parsing Error: ' + err.message);
        process.exit(1);
    });