<%

include("constants.jag");

var log = new Log();
var identityServerURL = Packages.org.wso2.carbon.identity.core.util.IdentityUtil;

function initI18N(){
	var i18n = session.get(I18N)
	if(i18n == null){
	    i18n = require(I18N);
	    i18n.init(request, "/" );
	    session.put(I18N, i18n);
	}
	return i18n;

}

function readFile(path){
	var file = new File(path);
	file.open("r");
	var json = "";

	json = file.readAll();
	file.close();
	json = parse(json);

	return json;
}

function sortNumber(jsonArray, property, ascending, zeroLast) {
    jsonArray.sort(function (a, b) {
        var aProp = parseFloat(a[property]);
        var bProp = parseFloat(b[property]);

        if(zeroLast){
             if(aProp == 0){
                aProp = 500000;
             }
             if(bProp == 0 ){
                bProp = 500000;
             }
        }

        return aProp === bProp ? 0 : ( ascending ? (aProp >= bProp ? 1 : -1 ) : (aProp >= bProp ? -1 : 1 ));
    });

    return jsonArray;
}




function getServerUrl(){
    return application.get(SERVER_URL);
}

function getSuccessErrorJson(request, i18n){
    var error = request.getParameter("e");
    var errorMsg = request.getParameter("error");
    var success = request.getParameter("s");
    var successMsg = request.getParameter("sMsg");

    var errorJson = {};

    if(error != null){
        if(errorMsg != null && errorMsg.length > 0){
            var temp = i18n.localize(errorMsg);
            errorJson.eMsg = (temp != null && temp.length > 0) ? temp : errorMsg;
        }else{
            errorJson.eMsg = i18n.localize("common_error");
        }
    }

    if(success != null && success === "1"){
        if(successMsg != null && successMsg.length > 0){
            var temp = i18n.localize(successMsg);
            errorJson.successMsg = (temp != null && temp.length > 0) ? temp : successMsg;
        }else{
            errorJson.successMsg = i18n.localize("common_success");
        }
    }

    return errorJson;

}

function doAuthenticate(obj){
    //this is the requested resource
    if(obj["login-required"] !== 'false'){
       if(session.get('user') == null){
            throw 'InvalidLogin';
       }
    }

    var permissions = obj.permissions;
    if(permissions != null){
        for each(var perm in permissions){
              if(!isAuthorized(perm)){
                throw 'NotAuthorized'
              }
        }
    }

}



function isAuthorized(resource){
    var perms = session.get(UI_USER_PERMISSIONS);
    if(perms == null) {
        return false;
    }

    for each(var p in perms){
        if(resource.indexOf(p) > -1){
            return true;
        }
    }

    return false;
}

function createLinkObject(obj, context, i18n){
	var tmp = {};
	tmp['link'] =  generateHeaderLink(obj, context, i18n);
	tmp['dash'] =  generateDashboard(obj, context, i18n);

	return tmp;
}

function generateHeader(loggedin, i18n){
}
function generateHeader2(loggedin, i18n){
	var uiComponents = application.get(UI_COMPONENTS);
	var pages = uiComponents.pages;
	var context = uiComponents.context;
	var accessiblePages = {};

	var logReqLinks = [];
	var logReqDash = [];
	var logNotReqLinks = [];
	var logNotReqDash = [];

	if(loggedin){
		for each(var obj in pages){
 	        try{
 	        	var pageLoginReq = obj['login-required'] === 'true';
 	        	if(pageLoginReq){

		        	doAuthenticate(obj);
		        	if(obj.displayorder != '-1' && obj['login-required']){
			        	var ob = createLinkObject(obj, context, i18n);
			        	logReqLinks.push(ob.link);
			        	logReqDash.push(ob.dash);
		        	}
 	        	}
	        }catch(e){
	        	//Ignore the exception
	        }
	    }
	}else{

		// only the pages that does not need a user login are displayed here
	    for each(var obj in pages){
	        if(obj['login-required'] && obj['login-required'] === 'false'){
	        	if(obj.displayorder != '-1'){
		        	var ob = createLinkObject(obj, context, i18n);
		        	logNotReqLinks.push(ob.link);
		        	logNotReqDash.push(ob.dash);
	        	}
	        }
	    }
	}

	var logReqLinkStr = "";
	for each(var obj in logReqLinks){
		logReqLinkStr += obj;
	}
	logReqLinks = logReqLinkStr;

	var logReqDashStr = "<div class='row'>";
	var count = 0;
	for each(var obj in logReqDash){
		logReqDashStr += obj;
		if(count == 3){
			logReqDashStr += "</div><div class='row second-row-gap'>";
			count = 0;
		}
		count++;
	}
	if(count < 3){
		logReqDashStr  += "</div>";
	}

	logReqDash = logReqDashStr;

	var logNotReqLinksStr = "";
	for each(var obj in logNotReqLinks){
		logNotReqLinksStr += obj;
	}
	logNotReqLinks = logNotReqLinksStr;


	var logNotReqDashStr = "";
	for each(var obj in logNotReqDash){
		logNotReqDashStr += obj;
	}
	logNotReqDash = logNotReqDashStr;

	accessiblePages['logReqLinks'] = logReqLinks;
	accessiblePages['logReqDash'] = logReqDash;
	accessiblePages['logNotReqLinks'] = logNotReqLinks;
	accessiblePages['logNotReqDash'] = logNotReqDash;

	return accessiblePages;
}

/**
 * accessiblePages - object containing page arrays
 */
function generateHeaderLink(page, context, i18n){

	var link = "<li class='"+ page.name +"' ><a title='"+ i18n.localize('pages')[page.text] +"' href='" + context + "/" + page.url +"'><i class='"+ page.styles +"'></i> <span><br>"+ i18n.localize('pages')[page.text] +"</span></a></li>";
	return link;

}

function generateDashboard(page, context, i18n){
	if(page['dashboard-styles']){

		var dashboard =     "<div class='col-md-4'>" +
							    "<div class='box-title'><h3>"+ i18n.localize('pages')[page.text] +"</h3></div>" +
							    "<div class='box-content'>" +
							        "<div class='" + page['dashboard-styles'] + "'></div>" +
							        i18n.localize('pages')[page.desc] +
							        "<p><a class='btn btn-default' href='"+ context + "/" + page.url +"'>View details &raquo;</a></p>" +
							    "</div>" +
						    "</div>";

		return dashboard;
	}
	return "";
}


String.prototype.replaceAll = function(stringToFind,stringToReplace){
    var temp = this;
    var index = temp.indexOf(stringToFind);
    while(index != -1){
        temp = temp.replace(stringToFind,stringToReplace);
        index = temp.indexOf(stringToFind);
    }
    return temp;
};

/*
 * Function to update server url information
 */
function setServerURL(isWebContextRootAvailable) {
    var serverUrl = stringify(application.get(SERVER_URL));
    if(serverUrl === 'null' || serverUrl == null || serverUrl.length <= 0){
        //Server URL is not specified in the jaggery.conf, therefore using the service url mentioned in the carbon.conf
        var carbon = require('carbon');
        var serverConfigService = carbon.server.osgiService('org.wso2.carbon.base.api.ServerConfigurationService');

        var path = "/conf/site.json";
        var file = new File(path);
        file.open("r");
        var json = file.readAll();
        file.close();

        var jsonConf = parse(json);
        var mgtTransport = "https";
        var serverCoreUrl = '';
        var proxyConfHost = jsonConf.proxy.proxyHost;
        var proxyConfPort = jsonConf.proxy.proxyHTTPSPort;
        var proxyOrigin = '';

        if (( proxyConfHost == null || proxyConfHost === '' || proxyConfHost === 'null' || proxyConfHost.length <= 0 )
            || ( proxyConfPort == null || proxyConfPort === '' || proxyConfPort === 'null' || proxyConfPort.length <=
                0 )) {
            //overriding carbon proxy settings configuration not available for ui urls
            proxyOrigin = identityServerURL.getServerURL("", false, false);
            if (log.isDebugEnabled()) {
                log.debug("Carbon proxy settings available in carbon.xml- Proxy Origin Name: " + proxyOrigin);
            }
        } else {
            //proxy settings available for ui urls
            if (log.isDebugEnabled()) {
                log.debug("site configuration ui url overiding available - Proxy Origin Name: " + proxyOrigin);
            }
            proxyOrigin = mgtTransport + "://" + proxyConfHost + ":" + proxyConfPort;
        }

        var proxyConfContextPath = jsonConf.proxy.proxyContextPath;
        if (proxyConfContextPath == null || proxyConfContextPath === '' || proxyConfContextPath === 'null' ||
            proxyConfContextPath.length <= 0) {
            //overriding carbon proxy settings configuration not available for ui urls
            proxyContextPath = serverConfigService.getFirstProperty(PROXY_CONTEXT_PATH);
        } else {
            //proxy settings available for ui urls
            if (log.isDebugEnabled()) {
                log.debug("site configuration ui url overiding available - Proxy Context Path : " +
                    proxyConfContextPath);
            }
            proxyContextPath = proxyConfContextPath;
        }

        var proxyContextPath = serverConfigService.getFirstProperty(PROXY_CONTEXT_PATH);
        if (proxyContextPath === 'null' || proxyContextPath == null || proxyContextPath === '' || proxyContextPath
            .length <= 0) {
            proxyContextPath = "";
        } else {
            if (proxyContextPath.indexOf('/') != 0) {
                proxyContextPath = '/' + proxyContextPath;
            }
        }
        //create server service url
        var serviceOrigin = '';
        if (jsonConf.service == undefined) {
            serviceOrigin = '';
        } else if (jsonConf.service.serviceOrigin == undefined) {
            serviceOrigin = '';
        } else {
            serviceOrigin = jsonConf.service.serviceOrigin;
        }

        if ( serviceOrigin == null || serviceOrigin === '' || serviceOrigin === 'null' || serviceOrigin.length <= 0 ){
            serverUrl = identityServerURL.getServerURL("services", true, true);
            if (isWebContextRootAvailable === 'false') {
                serverCoreUrl = identityServerURL.getServerURL("", true, false);
            } else {
                serverCoreUrl = identityServerURL.getServerURL("", true, true);
            }
        } else {
            serverCoreUrl = identityServerURL.fillURLPlaceholders(serviceOrigin);;
            serverUrl = serverCoreUrl + "/services";
        }

        application.put(MGT_TRANSPORT, mgtTransport);
        application.put(PROXY_ORIGIN, proxyOrigin);
        application.put(SERVER_URL, serverUrl);
        application.put(SERVER_CORE_URL, serverCoreUrl);
        application.put(PROXY_CONTEXT_PATH, proxyContextPath);

        if (log.isDebugEnabled()) {
            log.debug("Proxy Origin : " + proxyOrigin);
            log.debug("Server Url      :" + serverUrl);
            log.debug("Server Core Url :" + serverCoreUrl);
            log.debug("Proxy Context Path :" + proxyContextPath);
        }
    }
}

function getUserId(username, tenantDomain, userStoreDomain) {

    var carbon = require('carbon');
    var options = {};
    options.domain = tenantDomain;
    var tenantId = carbon.server.tenantId(options);
    var userSessionStore = Packages.org.wso2.carbon.identity.application.authentication.framework.store.UserSessionStore;
    return userSessionStore.getInstance().getUserId(username, tenantId, userStoreDomain);
}

%>
