// Globals /////////////////////////////////////////////////////////////////////
// [globals] -> web -> middleware -> views -> session -> routes -> index

// Functions ///////////////////////////////////////////////////////////////////
// necessary 'required' function
global.required = function (path) {
	return require(process.cwd() + '/' + path);
};

// Logger //////////////////////////////////////////////////////////////////////
var LogConfig = required('config/log');
global.log = require('./log')((LogConfig.show) ? LogConfig.show : 'info');

// Additional Globals //////////////////////////////////////////////////////////
var GlobalsConfig = required('config/globals');		// todo: globals config

// lodash
if (GlobalsConfig._) {
	global._ = require('lodash');					// global lodash
}

// DB //////////////////////////////////////////////////////////////////////////
var DBConfig = required('config/db');

// config data
var DB_PORT = DBConfig.port ? ':' + DBConfig.port : '';
var DB_ADDR = DBConfig.address ? DBConfig.address : 'localhost';
var DB_USER = DBConfig.username ? DBConfig.username : '';
var DB_PASS = DBConfig.password ? DBConfig.password : '';
var DB_DBNM = DBConfig.database ? DBConfig.database : '';

var DB_AUTH = '';
if (DB_USER !== '' || DB_PASS !== '') {
	DB_AUTH = DB_USER + ':' + DB_PASS + '@';
}

var DB_CONNECT = 'mongodb://' + DB_AUTH + DB_ADDR + DB_PORT + '/' + DB_DBNM;

// initialize database
var mongoose = require('bluebird').promisifyAll(require('mongoose'));
mongoose.connect(DB_CONNECT);

// mongo
var mongodb = mongoose.connection;
mongodb.on('error', log.error.bind(console, 'Connection error: '));
mongodb.once('open', function () {
	log.info('Database connected.');
});

// setup global variables
global.DB = {
	Schema: mongoose.Schema,
	Model: function (name, schema) {
		return mongoose.model(name, schema);
	}
};

// setup process variables
process.DB = {
	mongo: mongodb,
	mongoose: mongoose
};

// Models //////////////////////////////////////////////////////////////////////
if (GlobalsConfig.Models &&
	Array.isArray(GlobalsConfig.Models) &&
	GlobalsConfig.Models.length > 0) {

	global.Models = {};
	// add all models to global namespace
	GlobalsConfig.Models.forEach(function (model) {
		global.Models[model] = required('app/models/' + model);
	});
}

// Utils ///////////////////////////////////////////////////////////////////////
if (GlobalsConfig.Utils &&
	Array.isArray(GlobalsConfig.Utils) &&
	GlobalsConfig.Utils.length > 0) {

	global.Utils = {};
	// add all utils to global namespace
	GlobalsConfig.Utils.forEach(function (model) {
		global.Utils[model] = required('app/utils/' + model);
	});
}

// todo: std paths and chageable e.g. models directory paths
