"use strict";

var ServerConstants = require('../constants/ServerConstants');
var redisSessionStore = require('../redis/RedisSessionStore');

module.exports = function(cb) {

    redisSessionStore(function(err, sessionStore){
        if(err){
            cb(err);
            return;
        }

        var sessionOptions = {};
        var cookieOptions = {};

        var sessionConf = config.get('session');
        if (sessionConf && sessionConf.options) {
            sessionOptions = sessionConf.options;
        }

        var sessionSecret = config.get('sessionSecret');
        if (sessionSecret) {
            logger.warn("DEPRECATED: Please move the sessionSecret to be under session.options");
        }

        sessionOptions.secret = sessionSecret ? sessionSecret: sessionOptions.secret;

        if (!sessionOptions.secret) {
            cb(new Error("Session secret not found."));
            return;
        } else if (sessionStore) {
            if (sessionConf && sessionConf.options && sessionConf.options.cookie) {
                cookieOptions = sessionConf.options.cookie;
            }

            sessionOptions.key = ServerConstants.EXPRESS_KEY;
            sessionOptions.saveUninitialized = false;
            sessionOptions.resave = true;

            sessionOptions.cookie = cookieOptions;
            sessionOptions.store = sessionStore;
            cb(null, sessionOptions);
        } else {
            cb(new Error("Unable to get Redis session store!"));
        }
    });
};
