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 #6");
    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) {
            
            console.log("ERR: " + err);
            
            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:3000/auth/keycloak1/callback",
                    "autoRegister": true,
                    "successRedirect": "/index.html",
                    "failureRedirect": "/guest.html"                    
                }
            }
        },
        "adapters": {
            "adapter1": {
                "type": "jwt",
                "config": {
                    "cookie": "JWT",
                    "secret": "MIIClzCCAX8CBgFapBrZRDANBgkqhkiG9w0BAQsFADAPMQ0wCwYDVQQDDAR0ZXN0MB4XDTE3MDMwNjE0NTAwN1oXDTI3MDMwNjE0NTE0N1owDzENMAsGA1UEAwwEdGVzdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJ64FQLel2DLaH6l6/PZPFU3sT0M5icCf+xZ55feB5OEgwprSMD0Ys1k7k8lz9PJqLbpOTBWEUQXBGV594cUxjywDaFVBjQ9I7xAuz7QDVx+o2OWBlcWmOXjFYH/E11dKWcWv6F9wgnc2iHYe8v5XwWsxNX4Za7eCdKmasT3fMne/pSLrobbChAIrykoycH8332dPwiHkSzFI+gFt1AA5G0MybZXYebli1zaTiLaliF78zqBPMqgBnX123nr2dizMSTQe+mLUgtcjvB1se8nPg0SYmBarco3boPfavpQvFIXgUBiNzhqPingHsTLypQxUsQ1QJ3lUe+612QHi+JQJ4UCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAhyhuNdtz3wzahtyCyk3vIf8CokoV8pzAJ6fHm1SV1DFxf3lN3c9cj5ORpbnNV6rAHp3w8gK3YZruTvhJKqK7MHF6bRUXuxld419B3Y8fwVI/4aq9pZYsn5F+sbfbDoAlA8FU6Gt2LC5cx1FZiK5D7n9cuXS0fzAnTyDRiT6KHjiB2V6uirorqj3W8cU1PmRqRxER/mwasx2BsKpdyMKeE41BFjtaJ60uzBTVqD47kYCMZQUESd8+nIE0C8cZIQMNStNOFk9fbi1BAmXjV3ixovXkixeVm+kJc1FpZ+p0kxjJVjWi9fBhH7WyJS5UjoppCggwJk76jTG11eYU0krw3A=="
                }
            }
        },
        "filters": {
            "default": {
                "adapter": "adapter1",
                "provider": "keycloak1"
            }
        }
    }
});
