"use strict";

var q       = require("q");
var convict = require('convict');
var logger = require('../utils/Logger').loggers.get('main');

var serverEnv = "WEB_APP_SERVER";

if (process.env.GOBBLE_SERVER) {
    logger.warn("DEPRECATED: Please rename the GOBBLE_SERVER environment variable to WEB_APP_SERVER");

    serverEnv = "GOBBLE_SERVER";
}

/*eslint-disable */
var conf = convict({
  env: {
    doc: "The applicaton environment.",
    format: ["production", "development", "test"],
    default: "development",
    env: "NODE_ENV"
  },
  serv: {
    doc: "The Server environment.",
    format: "*",
    default: "development",
    env: serverEnv
  },
  ip: {
    doc: "The IP address to bind.",
    format: "ipaddress",
    default: "127.0.0.1",
    env: "IP_ADDRESS"
  },
  port: {
    doc: "The port to bind.",
    format: "port",
    default: 0,
    env: "PORT"
  },
  log_name: {
     doc: "The log file name.",
     format: "*",
     default: "log/formbird.log",
     env: "LOG_NAME"
  },
  max_log_size: {
     doc: "The maximum size of log file.",
     format: "int",
     default: "1048576",
     env: "MAX_SIZE"
  },
  max_log_file_count: {
     doc: "The maximum number of log file to keep.",
     format: "int",
     default: 5,
     env: "MAX_FILE_KEEP"
  },
  log_level:{
     doc:"The log level",
     format: ["silly", "debug", "verbose", "info", "warn", "error"],
     default:"debug",
     env:"LOG_LEVEL"
  },
  birt: {},
  offline: {},
  pmxOptions: {},
  urlBase: '',
});
/*eslint-enable */

// load environment dependent configuration
var serv = conf.get('serv');
conf.loadFile('./server/config/' + serv + '.json');

module.exports.get = function(key) {
    var val;

    try {
        val = conf.get(key);
    } catch(e) {}

    return val;
};

module.exports.getAll = function() {
    return conf;
};

module.exports.load = function () {
	var deferred = q.defer();

    var DatabaseConfig = require('../database/providers/DatabaseConfig');

    var dbConfigLoad = DatabaseConfig.getConfig(conf);
	dbConfigLoad(conf).then(function success(conf) {
		deferred.resolve(conf);
	},function error(err) {
		deferred.reject(err);
	});

	//perform validation
    conf.validate({ allowed: true});
	return deferred.promise;
};
