/*
 * Copyright 2005-2007 WSO2, Inc. (http://wso2.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*This js will be dynamically loaded */

var CONFIGURATION_SCENARIO_GROUP = "configurationScenarioGroup";

var scenarioId;
var scenarioIdForWS;
var scenarioSummary;
var scenarioCategory;


/* This will execute the correct secnario based on the server information
   CheckboxExecutor.execute(); will set on specific scenario
*/

/*
Variable that holds the catagory information
*/

var utRelated;
// ut.related function
var keystoreRelated;
// keystore.related function
var utkeystoreRelated;

var utRelatedString = "ut.related";
var keystoreRelatedString = "keystore.related";
var utkeystoreRelatedString = "ut.keystore.related";
var systemString = "system";

/* vaiables that holds the functions of scenarios */
var DisableSecurity;

/* This variable is flaged if the scenario is selected or not*/
var isUserSelectedScenario = false;

function getScenarioId() {
    return scenarioId;
}

function getScenarioIdForWS() {
    return scenarioIdForWS;
}

function getScenarioSummary() {
    return scenarioSummary;
}

function getScenarioCategory() {
    return scenarioCategory;
}

function CheckboxExecutor() {
}

function validateRS(category, scenario, summary) {
    if (category && scenario && !isUserSelectedScenario) {
        // do the initital firing if needed
        isUserSelectedScenario = false;
        scenarioId = scenario;
        scenarioIdForWS = scenario;
        scenarioSummary = summary;
        scenarioCategory = category;
        checkboxExecutorHelper(category, scenario);
        validateRSCheckboxExecutorHelper();


    } else {
        var isChecked = false;
        isUserSelectedScenario = false;
        // This will stabilizes the back button
        var objs = document.getElementsByName(CONFIGURATION_SCENARIO_GROUP);
        if (objs != null) {
            var objsLength = objs.length;
            for (var i = 0; i < objsLength; i++) {
                if (objs[i].checked) {
                    isChecked = true;
                    break;
                }
            }

        } else {
            wso2.wsf.Util.alertWarning("Problem encountered in javascript");
            return false;
        }

        if (!isChecked) {
            wso2.wsf.Util.alertMessage("Please select a scenario");
            return false;
        }
        //Execute with proper params
        validateRSCheckboxExecutorHelper();

    }
}

/*
This function will not be closed for modification
*/
function setCheckboxExecutor(category, scenario, summary) {

    isUserSelectedScenario = true;
    scenarioId = scenario;
    scenarioIdForWS = scenario;
    scenarioSummary = summary;
    scenarioCategory = category;
    checkboxExecutorHelper(category, scenario);
    return true;
}

/*private*/
function checkboxExecutorHelper(category, scenario) {
    if (category == utRelatedString) {
        CheckboxExecutor.execute = utRelated;
    } else if (category == keystoreRelatedString) {
        CheckboxExecutor.execute = keystoreRelated;
    }else if (category == utkeystoreRelatedString) {
        CheckboxExecutor.execute = utkeystoreRelated;
    }else if (category == systemString) {
        CheckboxExecutor.execute = DisableSecurity;
    }
}

/* utilities */
function FunctionInitiator() {
}

/*
rootElementName = name of the root element
divObjectName = name of the intitial object name
scenarioXsl = location of the rampart xsls
startingFunction = function should start first
*/
function rampartScenarioInitiator(rootElementName, divObjName, scenarioXsl, startingFunction,
                                  paramArray) {

    var tmpTransformationNode;

    if (window.XMLHttpRequest && !wso2.wsf.Util.isIE()) {
        tmpTransformationNode =
        document.implementation.createDocument("", rootElementName, null);
    } else if (window.ActiveXObject) {
        tmpTransformationNode = new ActiveXObject("Microsoft.XmlDom");

        var sXml = "<" + rootElementName + "></" + rootElementName + ">";

        tmpTransformationNode.loadXML(sXml);
    }
    var objDiv = document.getElementById(divObjName);
    rampartSpecificTransformer(tmpTransformationNode, scenarioXsl, objDiv, false, paramArray);
    wso2.wsf.Util.showOnlyOneMain(objDiv);
    FunctionInitiator.execute = startingFunction;
    // Execute the first function
    FunctionInitiator.execute();

}

/*private*/
function validateRSCheckboxExecutorHelper() {
    if (getScenarioCategory() == utRelatedString) {
        CheckboxExecutor.execute();
    } else if (getScenarioCategory() == keystoreRelatedString) {
        CheckboxExecutor.execute("genericScenarioInitializer", "divKeystoreRelated", "scenario2.xsl", listTrustStores, [getScenarioSummary()]);
    } else if (getScenarioCategory() == utkeystoreRelatedString) {
        CheckboxExecutor.execute("genericScenarioInitializer", "divUtKeystoreRelated", "scenario3.xsl", utkeystoreRelatedStart, [getScenarioSummary()]);
    } else if (getScenarioCategory() == systemString) {
        CheckboxExecutor.execute();
    }
}

/* scenarios */
/* ==================== utRelated starts =================*/
utRelated = function() {
    utRelatedWSCall();
}

function utRelatedWSCall() {
    var body_xml = '<req:getSecurityAssignment xmlns:req="http://org.apache.axis2/xsd">\n' +
                   '<serviceId>' + getServiceSpecificName() + '</serviceId>\n' +
                   '<serviceVersion></serviceVersion>\n' +
                   '</req:getSecurityAssignment>\n';

    var callURL = serverURL + "/" + SECURITY_SCENARIO_CONFIG_ADMIN ;
    new wso2.wsf.WSRequest(callURL, "getSecurityAssignment", body_xml, utRelatedWSCallCallback);

}
function utRelatedWSCallCallback() {
    var xmlData = this.req.responseXML;
    rampartSpecificTransformer(xmlData, "scenario1.xsl", document.getElementById('divUtRelated'), false, [getScenarioSummary()]);
    wso2.wsf.Util.showOnlyOneMain(document.getElementById('divUtRelated'));
    showlistServiceUsersHeader(document.getElementById('listServiceUsersHeader'));


}

function assignUsersAndRoles() {
    var usersObjects = document.getElementsByName('assignUserToServiceName');
    var rolesObjects = document.getElementsByName('assignRoleToServiceName');

    var users = "";
    var roles = "";
    var usersChecked = false;
    var rolesChecked = false;

    for (var i = 0; i < usersObjects.length; i++) {
        if (usersObjects[i].checked) {
            users +=
            '<users><![CDATA[' + usersObjects[i].value +
            ']]></users>';
            usersChecked = true;
        }
    }

    for (var i = 0; i < rolesObjects.length; i++) {
        if (rolesObjects[i].checked) {
            roles +=
            '<roles><![CDATA[' + rolesObjects[i].value +
            ']]></roles>';
            rolesChecked = true;
        }
    }

    if (!usersChecked && !rolesChecked) {
        wso2.wsf.Util.alertMessage("Please select at least one user or a role");
        return false;
    }
    if (usersChecked && !rolesChecked) {
        roles = "<roles nillable=\"true\"></roles>";

    }
    if (!usersChecked && rolesChecked) {
        users = "<users nillable=\"true\"></users>";
    }


    var body_xml = '<ns1:assignUsersAndRoles xmlns:ns1="http://org.apache.axis2/xsd">\n' +
                   '<serviceName>' + getServiceSpecificName() + '</serviceName>' +
                   '<serviceVersion></serviceVersion>' +
                   '<scenarioId>' + getScenarioId() + '</scenarioId>' +
                   users +
                   roles +
                   '</ns1:assignUsersAndRoles>';
    var callURL = serverURL + "/" + SECURITY_SCENARIO_CONFIG_ADMIN ;
    new wso2.wsf.WSRequest(callURL, "assignUsersAndRoles", body_xml, assignUsersAndRolesCallback);

}

function assignUsersAndRolesCallback() {

    wso2.wsf.Util.alertMessage("Security scenario successfully applied");

    showSecurityConfigurationInfo();

}

function listUsers1() {
    var body_xml = '<req:getServiceUsersWithDescriptionRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   '<req:serviceName>' + serviceSpecificName + '</req:serviceName>\n' +
                   '</req:getServiceUsersWithDescriptionRequest>\n';

    var callURL = serverURL + "/" + "ServiceAdmin" ;
    new wso2.wsf.WSRequest(callURL, "getServiceUsersWithDescription", body_xml, listUsersCallback1);
}

function listUsersCallback1() {

    transformationWithoutHistory(this.req.responseXML, "rampart/scenario1.xsl", document.getElementById("divServiceUNameToeknAuthUsers"));
    loadUsersComboBox1();
}

function loadUsersComboBox1() {
    var xsltFileName = "user.xsl";
    var body_xml = '<req:getUsersRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   ' </req:getUsersRequest>\n';

    var callURL = serverURL + "/" + "UserAdmin" + "/" ;
    new wso2.wsf.WSRequest(callURL, body_xml, "getUsers", loadUsersCallback1);
}

function loadUsersCallback1() {

    var optionBoxHTML = "";
    var comboToLoad = document.getElementById('serviceUserName');
    var data = this.req.responseXML;
    var rets = data.getElementsByTagName("return");
    var len = rets.length;
    var count;
    for (count = 0; count < len; count++) {
        comboToLoad.options[count] = new Option(rets[count].firstChild.nodeValue);
        comboToLoad.options[count].value = rets[count].firstChild.nodeValue;
    }
    listRoles1();
}

function listRoles1() {
    var body_xml = '<req:getServiceRolesWithDescriptionRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   '<req:serviceName>' + serviceSpecificName + '</req:serviceName>\n' +
                   '</req:getServiceRolesWithDescriptionRequest>\n';

    var callURL = serverURL + "/" + "ServiceAdmin" ;
    new wso2.wsf.WSRequest(callURL, "getServiceRolesWithDescription", body_xml, listRolesCallback1);

}

function listRolesCallback1() {

    transformationWithoutHistory(this.req.responseXML, "rampart/scenario1.xsl", document.getElementById("divServiceUNameToeknAuthRoles"));
    showlistServiceUsersHeader(document.getElementById('listServiceUsersHeader'));
    document.getElementById('divServiceUNameToeknAuthUsers').style.display = "inline";
    document.getElementById('listServiceUsersHeader').style.display = "inline";
    loadRolesComboBox1();

}


/* ================username and role assinging and deleting ===================  */

function assignUserToService(userName) {

    var un = userName[userName.selectedIndex].value;

    var body_xml = '<ns1:assignUserToService xmlns:ns1="http://org.apache.axis2/xsd">\n' +
                   '<serviceId>' + getServiceSpecificName() + '</serviceId>' +
                   '<serviceVersion></serviceVersion>' +
                   '<username>' + un + '</username>' +
                   '</ns1:assignUserToService>';
    var callURL = serverURL + "/" + SECURITY_SCENARIO_CONFIG_ADMIN ;
    new wso2.wsf.WSRequest(callURL, "assignUserToService", body_xml, assignUserToServiceCallback);
}

function assignUserToServiceCallback() {
    serviceUNameToeknAuth();
}

function assignRoleToService(role) {

    var rr = role[role.selectedIndex].value;

    var body_xml = '<ns1:assignRoleToService xmlns:ns1="http://org.apache.axis2/xsd">\n' +
                   '<serviceId>' + getServiceSpecificName() + '</serviceId>' +
                   '<serviceVersion></serviceVersion>' +
                   '<role>' + rr + '</role>' +
                   '</ns1:assignRoleToService>';

    var callURL = serverURL + "/" + SECURITY_SCENARIO_CONFIG_ADMIN ;
    new wso2.wsf.WSRequest(callURL, "assignRoleToService", body_xml, assignRoleToServiceCallback);
}

function assignRoleToServiceCallback() {
    serviceUNameToeknAuth();
}

function unassignUserFromService(userName) {
    var deleteIt = confirm("Do you really want to unassign user " + userName + " from " +
                           serviceSpecificName + " service?");
    if (deleteIt) {
        var body_xml = '<ns1:unassignUserFromService xmlns:ns1="http://org.apache.axis2/xsd">\n' +
                       '<serviceId>' + getServiceSpecificName() + '</serviceId>' +
                       '<serviceVersion></serviceVersion>' +
                       '<username>' + userName + '</username>' +
                       '</ns1:unassignUserFromService>';

        var callURL = serverURL + "/" + SECURITY_SCENARIO_CONFIG_ADMIN ;
        new wso2.wsf.WSRequest(callURL, "unassignUserFromService", body_xml, unassignUserRoleFromServiceCallback);
    }
}

function unassignRoleFromService(role) {
    var deleteIt = confirm("Do you really want to unassign role " + role + " from " +
                           serviceSpecificName + " service?");
    if (deleteIt) {
        var body_xml = '<ns1:unassignRoleFromService xmlns:ns1="http://org.apache.axis2/xsd">\n' +
                       '<serviceId>' + getServiceSpecificName() + '</serviceId>' +
                       '<serviceVersion></serviceVersion>' +
                       '<role>' + role + '</role>' +
                       '</ns1:unassignRoleFromService>';

        var callURL = serverURL + "/" + SECURITY_SCENARIO_CONFIG_ADMIN ;
        new wso2.wsf.WSRequest(callURL, "unassignRoleFromService", body_xml, unassignUserRoleFromServiceCallback);
    }
}

function unassignUserRoleFromServiceCallback() {
    utRelated();
}

/* =========== utRelated ends ==================*/

/* =========== keystoreRelated starts ================
 rootElementName
 divObjectName
 scenarioXsl
 startingFunction
 paramArray

*/
keystoreRelated =
function(rootElementName, divObjectName, scenarioXsl, startingFunction, paramArray) {
    rampartScenarioInitiator(rootElementName, divObjectName, scenarioXsl, startingFunction, paramArray);

}

function listTrustStores() {
    var body_xml = '<ns1:getServiceKeyStores xmlns:ns1="http://org.apache.axis2/xsd">\n' +
                   '<serviceName>' + getServiceSpecificName() + '</serviceName>\n' +
                   '</ns1:getServiceKeyStores>';
    var callURL = serverURL + "/" + CRYPTO_ADMIN_STRING ;
    new wso2.wsf.WSRequest(callURL, "getServiceKeyStores", body_xml, listTrustStoresCallback);
}

function listTrustStoresCallback() {

    /*var data = getBody(xhReq.responseXML);
    alert(xmlSerializerToString(data));*/

    rampartSpecificTransformationWithoutHistory(this.req.responseXML, "scenario2.xsl", document.getElementById("divAvailableCertifcateStores"));
    showlistServiceUsersHeader(document.getElementById('genericScenarioHeader'));
    document.getElementById('divButtonRawForGenericScenario').style.display = "inline";
}

function assignKeyStores() {

    var certificateStoresCheckboxObj = document.getElementsByName('trustedCertificateStoreNames');
    var privateKeystoreSelectObj = document.getElementById('privateKeystoreForServer');

    var privateKeystoreSelectObjValue = privateKeystoreSelectObj[privateKeystoreSelectObj.selectedIndex].value;

    if ((certificateStoresCheckboxObj == null) || (privateKeystoreSelectObj == null)) {
        wso2.wsf.Util.alertWarning("Either trusted certificate stores or private keystores not available ");
    }
    var trustedCertStores = "";
    var certificateStoresCheckboxObjLength = certificateStoresCheckboxObj.length;
    var isCertificateStoresCheckboxObj = false;
    for (var i = 0; i < certificateStoresCheckboxObjLength; i++) {
        if (certificateStoresCheckboxObj[i].checked) {
            trustedCertStores +=
            '<trustedCertStores>' + certificateStoresCheckboxObj[i].value +
            '</trustedCertStores>\n';
            isCertificateStoresCheckboxObj = true;
        }
    }

    if (!isCertificateStoresCheckboxObj) {
        wso2.wsf.Util.alertMessage("Please select at least one Trusted Certificate Store");
        return false;
    }

    var body_xml = '<ns1:assignKeyStores xmlns:ns1="http://org.apache.axis2/xsd">\n' +
                   '<serviceName>' + getServiceSpecificName() + '</serviceName>\n' +
                   '<scenarioId>' + getScenarioIdForWS() + '</scenarioId>\n' +
                   trustedCertStores +
                   '<privateKeyStore>' + privateKeystoreSelectObjValue + '</privateKeyStore>\n' +
                   '</ns1:assignKeyStores>\n';

    var callURL = serverURL + "/" + SECURITY_SCENARIO_CONFIG_ADMIN ;
    new wso2.wsf.WSRequest(callURL, "assignKeyStores", body_xml, assignKeyStoresCallback);

}

function assignKeyStoresCallback() {

    wso2.wsf.Util.alertMessage("Security scenario successfully applied");
    showSecurityConfigurationInfo();
}

/* =========== keystoreRelated ends ================= */


/* =========== UtKeystoreRelated starts ============= */

utkeystoreRelated =
function(rootElementName, divObjectName, scenarioXsl, startingFunction, paramArray) {
    rampartScenarioInitiator(rootElementName, divObjectName, scenarioXsl, startingFunction, paramArray);
}

function utkeystoreRelatedStart() {
    var body_xml = '<req:getUtKeystoreSecurityAssignment xmlns:req="http://org.apache.axis2/xsd">\n' +
                   '<serviceName>' + getServiceSpecificName() + '</serviceName>\n' +
                   '</req:getUtKeystoreSecurityAssignment>\n';

    var callURL = serverURL + "/" + SECURITY_SCENARIO_CONFIG_ADMIN ;
    new wso2.wsf.WSRequest(callURL, "urn:getUtKeystoreSecurityAssignment", body_xml, utkeystoreRelatedStartCallback);
}

function utkeystoreRelatedStartCallback() {
    rampartSpecificTransformationWithoutHistory(this.req.responseXML, "scenario3.xsl", document.getElementById("divAvailableUtKeystoreInternal"));
    showlistServiceUsersHeader(document.getElementById('genericScenarioHeader'));
    document.getElementById('divButtonRawForGenericScenario').style.display = "inline";
}

function assignUsersAndRolesAndKeystores() {
    var usersObjects = document.getElementsByName('assignUserToServiceName');
    var rolesObjects = document.getElementsByName('assignRoleToServiceName');

    var users = "";
    var roles = "";
    var usersChecked = false;
    var rolesChecked = false;

    for (var i = 0; i < usersObjects.length; i++) {
        if (usersObjects[i].checked) {
            users +=
            '<users><![CDATA[' + usersObjects[i].value +
            ']]></users>';
            usersChecked = true;
        }
    }

    for (var i = 0; i < rolesObjects.length; i++) {
        if (rolesObjects[i].checked) {
            roles +=
            '<roles><![CDATA[' + rolesObjects[i].value +
            ']]></roles>';
            rolesChecked = true;
        }
    }

    if (!usersChecked && !rolesChecked) {
        wso2.wsf.Util.alertMessage("Please select at least one user or a role");
        return false;
    }
    if (usersChecked && !rolesChecked) {
        roles = "<roles nillable=\"true\"></roles>";

    }
    if (!usersChecked && rolesChecked) {
        users = "<users nillable=\"true\"></users>";
    }

    var certificateStoresCheckboxObj = document.getElementsByName('trustedCertificateStoreNames');
    var privateKeystoreSelectObj = document.getElementById('privateKeystoreForServer');

    var privateKeystoreSelectObjValue = privateKeystoreSelectObj[privateKeystoreSelectObj.selectedIndex].value;

    if ((certificateStoresCheckboxObj == null) || (privateKeystoreSelectObj == null)) {
        wso2.wsf.Util.alertWarning("Either trusted certificate stores or private keystores not available ");
    }
    var trustedCertStores = "";
    var certificateStoresCheckboxObjLength = certificateStoresCheckboxObj.length;
    var isCertificateStoresCheckboxObj = false;
    for (var i = 0; i < certificateStoresCheckboxObjLength; i++) {
        if (certificateStoresCheckboxObj[i].checked) {
            trustedCertStores +=
            '<trustedCertStores>' + certificateStoresCheckboxObj[i].value +
            '</trustedCertStores>\n';
            isCertificateStoresCheckboxObj = true;
        }
    }

    if (!isCertificateStoresCheckboxObj) {
        wso2.wsf.Util.alertMessage("Please select at least one Trusted Certificate Store");
        return false;
    }

    var body_xml = '<ns1:assignUsersAndRolesAndKeyStores xmlns:ns1="http://org.apache.axis2/xsd">\n' +
                   '<serviceName>' + getServiceSpecificName() + '</serviceName>\n' +
                   '<serviceVersion></serviceVersion>\n' + 
                   '<scenarioId>' + getScenarioIdForWS() + '</scenarioId>\n' +
                   trustedCertStores +
                   '<privateKeyStore>' + privateKeystoreSelectObjValue + '</privateKeyStore>\n' +
                   users +
                   roles +
                   '</ns1:assignUsersAndRolesAndKeyStores>\n';

    var callURL = serverURL + "/" + SECURITY_SCENARIO_CONFIG_ADMIN ;
    new wso2.wsf.WSRequest(callURL, "urn:assignUsersAndRolesAndKeyStores", body_xml, assignKeyStoresCallback);
}

/* =========== UtKeystoreRelated ends =============== */

/* ============= disableSecurity ============== */
DisableSecurity = function() {
    var body_xml = '<ns1:disableSecurity xmlns:ns1="http://org.apache.axis2/xsd">\n' +
                   '<serviceName>' + getServiceSpecificName() + '</serviceName>' +
                   '</ns1:disableSecurity>';

    var callURL = serverURL + "/" + SECURITY_SCENARIO_CONFIG_ADMIN ;
    new wso2.wsf.WSRequest(callURL, "disableSecurity", body_xml, DisableSecurityCallback);
}

function DisableSecurityCallback() {

    wso2.wsf.Util.alertMessage("Security has been disabled for service [" +
                               getServiceSpecificName() + "]");
    showSecurityConfigurationInfo();
}

function rampartBackButton() {
    showSecurityConfigurationInfo();
}


