'use strict';

const {
    getClientConfigurationScript,
    getConfiguration,
    setClientConfigurationScript,
    setConfiguration
} = require('../redis/RedisConfigurationService');

const {
    buildClientConfigScript
} = require('../utils/UtilConfig');


module.exports.loadClientConfig = function(req, res) {


    getClientConfigurationScript().then((confScript) => {
        if (confScript) {
            return Promise.resolve(confScript);
        } else {
            return new Promise((resolve, reject) => {
                getConfiguration().then(configDocRedis => {
                    if (configDocRedis) {
                        var clientConf = configDocRedis.clientConfiguration;
                        setClientConfigurationScript(clientConf);

                        resolve(buildClientConfigScript(clientConf));
                    } else {
                        config.load().then(() => {
                            var configDoc = config.get('');
                            setConfiguration(configDoc);

                            resolve(buildClientConfigScript(configDoc.clientConfiguration));
                        }, err => {
                            reject(err);
                        });
                    }
                });
            });
        }
    }).then(configJS => {
        res.type('.js');
        res.write(configJS);
        res.end();
    }).catch((error) => {
        logger.error("Fatal error loading configuration - " + error);
        res.sendStatus(404);
    });
};
