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 #4");
    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);            
        });        
    });
    
    callback();
});

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

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

    callback();
});

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

    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");
        });        
    });
    
    app.get("/cookie/delete", function(req, res) {
        
        var cookieName = process.configuration.auth.adapters.adapter1.config.cookie;
        res.clearCookie(cookieName);
        
        res.redirect("/index.html");
    });

    callback();
});

/**
 * Start the Server
 */
server.start({
    "setup": "single",
    "viewEngine": "dust",
    "welcome": {
        "enabled": true,
        "file": "index.html"
    },
    "session": {
        "enabled": 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",
                    "autoRegister": true,
                    "successRedirect": "/index.html",
                    "failureRedirect": "/guest.html"                    
                }
            }
        },
        "adapters": {
            "adapter1": {
                "type": "jwt",
                "config": {
                    "cookie": "JWT",
                    "trusted": false
                }
            }
        },
        "filters": {
            "default": {
                "adapter": "adapter1",
                "provider": "keycloak1"
            }
        }
    }
});
