var q = require("q");
var RedisKeys = require('../constants/RedisKeys');
var { getRedisClient } = require('./RedisClient');
var { buildClientConfigScript } = require('../utils/UtilConfig');

const get = (key, cb) => {

  getRedisClient().get(key, function(err, result) {
        if (err) {
            cb();
        } else {
            cb(null, result);
        }
    });


};

const set = (key, config) => {
  getRedisClient().set(key, config);
};

/* PUBLIC API */

const getClientConfigurationScript = () => {
    var deferred = q.defer();

    var redisKey = RedisKeys.DOCUMENTS_SCRIPTS_PREFIX + RedisKeys.CLIENT_CONFIG_REDIS_KEY;
    get(redisKey, (err, clientConfigScript) => {
        if (err) {
            deferred.resolve();
        } else {
            deferred.resolve(clientConfigScript);
        }
    });

    return deferred.promise;
};

const getConfiguration = () => {
    var deferred = q.defer();

    var redisKey = RedisKeys.CONFIG_REDIS_KEY;

    get(redisKey, (err, configDocument) => {
        if (err) {
            deferred.resolve();
        } else {
            logger.debug("Got configuration from Redis: " + redisKey);
            deferred.resolve(JSON.parse(configDocument));
        }
    });

    return deferred.promise;
};

const setClientConfigurationScript = clientConfig => {
    var clientConfRedisKey = RedisKeys.DOCUMENTS_SCRIPTS_PREFIX + RedisKeys.CLIENT_CONFIG_REDIS_KEY;
    if (clientConfig) {
        var configJS = buildClientConfigScript(clientConfig);
        set(clientConfRedisKey, configJS);
    }
};

const setConfiguration = configDocument => {
    var confRedisKey = RedisKeys.CONFIG_REDIS_KEY;

    set(confRedisKey, JSON.stringify(configDocument));
    setClientConfigurationScript(configDocument.clientConfiguration);
};

module.exports = {
    getClientConfigurationScript,
    getConfiguration,
    setClientConfigurationScript,
    setConfiguration
};
