var server = require("cloudcms-server/server");
var KeycloakUtils = require("keycloak-auth-utils");

process.env.PORT = 4000;

/**
 * This gets displayed once the server starts up.
 */
server.report(function(callback) {

    console.log("");
    console.log("Cloud CMS Application Server - Example #5");
    console.log("");
    console.log("Node Version: " + process.version);
    console.log("Server Version: " + process.env.CLOUDCMS_APPSERVER_PACKAGE_VERSION);
    console.log("Server Mode: " + process.env.CLOUDCMS_APPSERVER_MODE);
    console.log("");
    console.log("Web Server: http://localhost:" + process.env.PORT);
    console.log("");

    callback();
});

var render = function(req, res, filepath, title, model)
{
    if (!model) {
        model = {};
    }
    
    model.title = title;

    if (req.user) {
        model.user = req.user;
    }

    res.render(filepath, model);
};

// protected routes
server.routes(function(app, callback) {

    var auth = app.auth("default");
    
    app.get("/index.html", auth, function(req, res) {

        var model = {
            "user": req.user,
            "userJSON": JSON.stringify(req.user, null, 3),
            "documents": []
        };
        
        req.gitana_user_connection.datastore("content").readBranch("master").queryNodes({}, {
            "limit": 10
        }).each(function() {
            model.documents.push(this);
        }).then(function() {
            render(req, res, "index.html", "My Documents", model);            
        });        
    });
        
    app.get("/cookie/delete", auth, function(req, res) {        
        
        if (req.gitana_user) {
            Chain(req.gitana_user).del();            
        }

        var cookieName = process.configuration.auth.adapters.adapter1.config.cookie;        
        res.clearCookie(cookieName);
        
        res.redirect("/index.html");
    });    
    
    callback();
});

// guest routes
server.routes(function(app, callback) {

    app.get("/guest.html", function(req, res) {
        render(req, res, "guest.html", "You are not authenticated");
    });

    app.get("/registration.html", function(req, res) {
        
        var model = {};

        if (req.session.registration_user_object) {
            model.user = req.session.registration_user_object;
            
            var errors = req.flash("errors");
            if (errors) {
                model.errors = errors;
            }
            
            model.hasErrors = (model.errors.length > 0);
        }
        
        render(req, res, "registration.html", "You are not authenticated", model);
    });
    
    app.get("/cookie/create", function(req, res) {
        
        var kc = process.configuration.auth.providers.keycloak1.config;
        var grantManager = new KeycloakUtils.GrantManager({
            "realmUrl": kc.auth_server_url + "/realms/" + kc.realm,
            "clientId": kc.clientID,
            "secret": kc.clientSecret,
            "minTimeBetweenJwksRequests": 0
        });
        grantManager.obtainDirectly("test", "test", function(err, grant) {

            if (err) {
                return res.status(503).end();
            }

            var accessToken = grant.access_token.token;
            
            var cookieName = process.configuration.auth.adapters.adapter1.config.cookie;
            res.cookie(cookieName, accessToken);
            res.redirect("/index.html");
        });        
    });

    callback();
});

/**
 * Start the Server
 */
server.start({
    "setup": "single",
    "viewEngine": "dust",
    "welcome": {
        "enabled": true,
        "file": "index.html"
    },
    "session": {
        "enabled": true,
        "type": "memory"
    },
    "registration": {
        "enabled": true,
        "options": {
            "passwords": false,
            "email": false,
            "usename": false
        }
    },
    "auth": {
        "enabled": true,
        "providers": {
            "keycloak1": {
                "type": "keycloak",
                "config": {
                    "realm": "master",
                    "auth_server_url": "http://localhost:9090/auth",
                    "clientID": "test",
                    "clientSecret": "4be973e0-2c1a-411b-bf94-b614237edb4a",
                    "callbackURL": "http://localhost:4000/auth/keycloak1/callback",
                    "failureRedirect": "/guest.html",                
                    "registrationRedirect": "/registration.html"                    
                }
            }
        },
        "adapters": {
            "adapter1": {
                "type": "jwt",
                "config": {
                    "cookie": "JWT"
                }                
            }
        },
        "filters": {
            "default": {
                "adapter": "adapter1",
                "provider": "keycloak1"
            }
        }
    }
});
