'use strict';

var q = require("q");
var couchbase = require('couchbase');
var CouchbaseConnection = require('./CouchbaseConnection');
var SharedConstants = require('../../../../shared/constants/SharedConstants');
var logger = require('../../../utils/Logger').loggers.get('db');
var utilConfig = require('../../../utils/UtilConfig');
var dbConfig = require('../DatabaseConfig');
var cbUtil = require('./CouchbaseUtil');

var loadConfig = function(deferred, conf, couchbaseConfig) {

    CouchbaseConnection.initialise().then(function () {
        var cbBucket = CouchbaseConnection.getBucket();
        var bucketName = couchbaseConfig.bucket;
        var statement = "SELECT `" + bucketName + "`.* FROM `" + bucketName + "` " +
            "WHERE systemHeader.systemType = $1 AND systemHeader.currentVersion = true;";

        var query = cbUtil.getN1QlQuery(statement);
        cbBucket.query(query, [SharedConstants.SYSTEM_TYPE_CONFIGURATION], function(err, results) {
            if (err) {
                var errorMsg = "Error finding config document in database: " + err;
                logger.error(errorMsg);
                deferred.reject(new Error(errorMsg));
            } else {
                var doc = results[0];
                if (doc) {
                    logger.info("Successfully loaded configuration document from database");
                    utilConfig.mergeConfigs(conf, doc, deferred);
                }  else {
                    var msg = "Config not found in the database, using the configuration from file " +
                        "with no database overrides";
                    logger.warn(msg);
                    deferred.resolve(conf);
                }
            }
        });
    },function errorFunc(err) {
        deferred.reject(err);
    });


};

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

    logger.info("Connecting to Couchbase database to load configuration");
    var couchbaseConfig = dbConfig.getDataServicesConfig();

    if (couchbaseConfig.userName && couchbaseConfig.password) {
        CouchbaseConnection.validateAuth(couchbaseConfig).then(function success(msg) {
            loadConfig(deferred, conf, couchbaseConfig);
        }, function error(err) {
            deferred.reject(err);
        });
    } else {
        loadConfig(deferred, conf);
    }

    return deferred.promise;
};