"use strict";

var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var { createRedisClient } = require("./RedisClient");

function redisTest(redisConfig, cb){

    var configOk = redisConfig && redisConfig.host && redisConfig.port;

    if(!configOk){
        cb(new Error('Invalid redis configuration.'));
        return;
    }

    if(redisConfig.disableRedisSessionStore){
        cb(new Error('Redis session store is disabled in the configuration.'));
        return;
    }

    var redis = createRedisClient(redisConfig);
    
    redis.on("error", function (err) {
        cb(err);
        redis.quit();
    });

    redis.on("ready", function () {
        cb();
        redis.quit();
    });

}

module.exports = function(cb) {

    var sessionConfig = require('./RedisConfig').getSessionConfig();

    redisTest(sessionConfig, function (err){
        if(err){
            logger.error("Please make sure redis is installed and configured");
            cb(err);
        } else {            
            const client = createRedisClient(sessionConfig);
            cb(null, new RedisStore({ client }));
        }
    });

};