/*
 * 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.
 */

var lastUsedModuleId = "";
var lastUsedModuleVersion = "";
var moduleXSLTFileName = "modules.xsl";
var moduleConfigureXSLTFileName = "configure_module.xsl";

function engageModuleForSystem(moduleId, moduleVersion) {
    var engage = confirm("Do you really want to globally engage the " + moduleId + " module?");
    if (engage == true) {
        var body_xml = '<ns1:engageModuleForSystem xmlns:ns1="http://org.apache.axis2/xsd">' +
                       '<ns1:moduleId>' + moduleId + '</ns1:moduleId>' +
                       '<ns1:moduleVersion>' + moduleVersion + '</ns1:moduleVersion>' +
                       '</ns1:engageModuleForSystem>';

        var callURL = serverURL + "/" + MODULE_ADMIN_STRING;
        new wso2.wsf.WSRequest(callURL,"engageModuleForSystem",body_xml,engageModuleForSystemCallback);
    }
}

function engageModuleForSystemCallback() {

    var data = this.req.responseXML;
    var text = data.getElementsByTagName('return')[0];

    wso2.wsf.Util.alertMessage(text.firstChild.nodeValue);
    listModules();
}

function disengageModuleForSystem(moduleId, moduleVersion) {

    var disengage = confirm("Do you really want to globally disengage the " + moduleId +
                            " module?");
    if (disengage == true) {
        var body_xml = '<ns1:disengageModuleFromSystem xmlns:ns1="http://org.apache.axis2/xsd">' +
                       '<ns1:moduleId>' + moduleId + '</ns1:moduleId>' +
                       '<ns1:moduleVersion>' + moduleVersion + '</ns1:moduleVersion>' +
                       '</ns1:disengageModuleFromSystem>';

        var callURL = serverURL + "/" + MODULE_ADMIN_STRING;
        new wso2.wsf.WSRequest(callURL,"disengageModuleFromSystem",body_xml,disengageModuleForSystemCallback);
    }
}

function disengageModuleForSystemCallback() {
    wso2.wsf.Util.alertMessage("Module was globally disengaged successfuly.");
    listModules();
}


function getLastUsedModuleId() {
    return lastUsedModuleId;
}

function getLastUsedModuleVersion() {
    return lastUsedModuleVersion;
}

/* Will get and display the parameters for the given module id and version. */
function getModuleParameters(moduleId, moduleVersion) {
    lastUsedModuleId = moduleId;
    lastUsedModuleVersion = moduleVersion;
    //hand make the request
    var body_xml = '<ns1:getModuleParametersRequest xmlns:ns1="http://org.apache.axis2/xsd">' +
                   '<ns1:moduleId>' + moduleId + '</ns1:moduleId>' +
                   '<ns1:moduleVersion>' + moduleVersion + '</ns1:moduleVersion>' +
                   '</ns1:getModuleParametersRequest>';

    var callURL = serverURL + "/" + MODULE_ADMIN_STRING;
    new wso2.wsf.WSRequest(callURL,"getModuleParameters",body_xml,function(){
        wso2.wsf.Util.callbackhelper(this.req.responseXML,moduleXSLTFileName,document.getElementById("divGetModuleParameters"));
    });

}


/* List modules - Will create an html object for a list of modules and will attach it to divListModules */
function listModules(thisObj, index) {

    if (thisObj && index) {
        renderSelectedMenuItem(thisObj, index);
        gatherHistoryObject(thisObj.id, index);
    }

    var body_xml = '<ns1:listModules  xmlns:ns1="http://org.apache.axis2/xsd"/>\n';

    var callURL = serverURL + "/" + MODULE_ADMIN_STRING + "/" + "listModules";
    //    send("listModules", body_xml, moduleXSLTFileName, callURL, document.getElementById("divListModules"), false);
    new wso2.wsf.WSRequest(callURL,"listModules",body_xml,listModulesCallback);
}

function listModulesCallback() {

    wso2.wsf.Util.callbackhelper(this.req.responseXML,moduleXSLTFileName, document.getElementById("divListModules"));
    // Observing the globally engage modules
    listGloballyEngageModulesForObservation();
}

function getModuleInfo(moduleId, moduleVersion) {

    var body_xml = '<ns1:getModuleInfo  xmlns:ns1="http://org.apache.axis2/xsd">\n' +
                   '<ns1:moduleId>' + moduleId + '</ns1:moduleId>\n' +
                   '<ns1:moduleVersion>' + moduleVersion + '</ns1:moduleVersion>\n' +
                   '</ns1:getModuleInfo>\n';

    var callURL = serverURL + "/" + MODULE_ADMIN_STRING;
    new wso2.wsf.WSRequest(callURL,"getModuleInfo",body_xml,getModuleInfoCallback);
}

function getModuleInfoCallback() {

    wso2.wsf.Util.callbackhelper(this.req.responseXML,"configure_module.xsl", document.getElementById("divConfigureModule"));
}

/* This will iterate through the list of parameter names and parameter values and calls the server
	to update that parameter with the new values. */
var cur_module_number = 0;
var global_arrayOfNames = null;
var global_arrayOfValues = null;
function processModuleConfigUpdate(arrayOfNames, arrayOfValues) {

    processMultipleModuleConfigEntry(getLastUsedModuleId(), getLastUsedModuleVersion(), arrayOfNames, arrayOfValues);
}

/* This is called by processModuleConfigUpdate for each name value pair. This will do the actual server
	call to update the parameter in question */

function processMultipleModuleConfigEntry(moduleId, moduleVersion, parameterNamesObj,
                                          parameterValueObj) {
    var paramElements = '';
    for (var i = 0; i < parameterNamesObj.length; i++) {
        paramElements += '<parameter locked="false" name="' + parameterNamesObj[i] + '"><![CDATA[' +
                         parameterValueObj[i] + ']]></parameter>\n';
    }

    var body_xml = '<ns1:setModuleParameters xmlns:ns1="http://org.apache.axis2/xsd">' +
                   '<ns1:moduleId>' + moduleId + '</ns1:moduleId>' +
                   '<ns1:moduleVersion>' + moduleVersion + '</ns1:moduleVersion>' +
                   paramElements +
                   '</ns1:setModuleParameters>';

    var callURL = serverURL + "/" + MODULE_ADMIN_STRING;
    new wso2.wsf.WSRequest(callURL,"setModuleParameters",body_xml,processMultipleModuleConfigEntryCallback);

}

function processMultipleModuleConfigEntryCallback() {

    wso2.wsf.Util.alertMessage("Module parameters were successfully updated.");

    getModuleParametersForConfig(getLastUsedModuleId(), getLastUsedModuleVersion());
}

function processSingleModuleConfigEntry(moduleId, moduleVersion, itemName, itemValue, callback) {

    if (!parseParameterName(itemName)) {
        wso2.wsf.Util.alertMessage("Parameter name contains an invalid character");
        return false;
    }

    var body_xml = '<ns1:setModuleParameterRequest xmlns:ns1="http://org.apache.axis2/xsd">' +
                   '<ns1:moduleId>' + moduleId + '</ns1:moduleId>' +
                   '<ns1:moduleVersion>' + moduleVersion + '</ns1:moduleVersion>' +
                   '<parameter locked="false" name="' + itemName + '"><![CDATA[' + itemValue +
                   ']]></parameter>' +
                   '</ns1:setModuleParameterRequest>';

    var callURL = serverURL + "/" + MODULE_ADMIN_STRING;
    new wso2.wsf.WSRequest(callURL,"setModuleParameter",body_xml,callback);
}

/* Used to show the value passed to the function to the user. This is tipicaly used to
	display whether an update was successful, etc. */
function updateModuleInfoDisplay(message) {
    document.getElementById('moduleConfigUpdate').innerHTML = message;
}


//add a new module parameter
function addModuleParameter() {
    var newParam = wso2.wsf.Util.getUserInput();
    if (newParam != null) {
        processSingleModuleConfigEntry(
                getLastUsedModuleId(),
                getLastUsedModuleVersion(),
                newParam[0],
                newParam[1], getModuleParametersForConfig);
    }
}

//remove a new module parameter
function removeModuleParameter(button) {
        processSingleModuleConfigEntryRemoval(
                getLastUsedModuleId(),
                getLastUsedModuleVersion(),
                button.id, getModuleParametersForConfig);
    
}

function processSingleModuleConfigEntryRemoval(moduleId, moduleVersion, itemName, callback) {

    if (!parseParameterName(itemName)) {
        wso2.wsf.Util.alertMessage("Parameter name contains an invalid character");
        return false;
    }

    var body_xml = '<ns1:removeModuleParameterRequest xmlns:ns1="http://org.apache.axis2/xsd">' +
                   '<ns1:moduleId>' + moduleId + '</ns1:moduleId>' +
                   '<ns1:moduleVersion>' + moduleVersion + '</ns1:moduleVersion>' +
                   '<parameter locked="false" name="' + itemName + '"></parameter>' +
                   '</ns1:removeModuleParameterRequest>';

    var callURL = serverURL + "/" + MODULE_ADMIN_STRING;
    new wso2.wsf.WSRequest(callURL,"removeModuleParameter",body_xml,callback);
}

/* Will get the parameters for the given module. Will display the returned data in
	divGetModuleParametersForConfig. */
function getModuleParametersForConfig(moduleId, moduleVersion) {
    //set the last Used module Id and version.
    if (moduleId == null) {
        moduleId = lastUsedModuleId;
    } else {
        lastUsedModuleId = moduleId;
    }
    if (moduleVersion == null) {
        moduleVersion = lastUsedModuleVersion;
    } else {
        lastUsedModuleVersion = moduleVersion;
    }

    var body_xml = '<ns1:getModuleParametersRequest xmlns:ns1="http://org.apache.axis2/xsd">' +
                   '<ns1:moduleId>' + moduleId + '</ns1:moduleId>' +
                   '<ns1:moduleVersion>' + moduleVersion + '</ns1:moduleVersion>' +
                   '</ns1:getModuleParametersRequest>';

    var callURL = serverURL + "/" + MODULE_ADMIN_STRING;
    new wso2.wsf.WSRequest(callURL,"getModuleParameters",body_xml,getModuleParametersForConfigCallback);

}

function getModuleParametersForConfigCallback() {

    wso2.wsf.Util.callbackhelper(this.req.responseXML,"configure_module_parameters.xsl", document.getElementById("divGetModuleParametersForConfig"));
    showconfigureModuleHeader(document.getElementById('configureModuleHeader'));
}

/* This will remove a module from the system */
function removeModule(moduleId, moduleVersion) {
    var delete_module = confirm("Do you really want to remove this module from the system?");
    if (delete_module == true) {
        var body_xml = '<ns1:removeModule xmlns:ns1="http://org.apache.axis2/xsd">' +
                       '<ns1:moduleId>' + moduleId + '</ns1:moduleId>' +
                       '<ns1:moduleVersion>' + moduleVersion + '</ns1:moduleVersion>' +
                       '</ns1:removeModule>';

        var callURL = serverURL + "/" + MODULE_ADMIN_STRING;
        new wso2.wsf.WSRequest(callURL,"removeModule",body_xml,removeModuleCallback);
    }
}

function removeModuleCallback() {

    listModules();
    stopWaitAnimation();
    var restart = confirm("Module was removed successfuly from the repository." +
                          "\n The server needs to be restarted for this to take effect." +
                          "\n Restart now?");
    if (restart) {
        wso2.wsf.Util.restartServer();
    }
}


function listGloballyEngageModulesForObservation() {
    body_xml = '<req:listGloballyEngagesModulesRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
               ' </req:listGloballyEngagesModulesRequest>\n';

    var callURL = serverURL + "/" + MODULE_ADMIN_STRING;
    new wso2.wsf.WSRequest(callURL,"listGloballyEngagesModules",body_xml,listGloballyEngageModulesForObservationCallback);

}

function listGloballyEngageModulesForObservationCallback() {

    wso2.wsf.Util.callbackhelper(this.req.responseXML,"list_engaged_modules_per_service.xsl", document.getElementById("listGloballyEngageModulesForObserve"), true);
    //    showgetModuleParameterHeader(document.getElementById('getModuleParameterHeader'));
}

////////////////////////////////////////////////////////////////////////////////
//                            <wsp:Policy> 				      //
////////////////////////////////////////////////////////////////////////////////


function getModulePolicies(moduleId, moduleVersion) {

    lastUsedModuleId = moduleId;
    lastUsedModuleVersion = moduleVersion;

    var body_xml = '<ns1:getPoliciesRequest xmlns:ns1="http://org.apache.axis2/xsd">' +
                   '<ns1:moduleId>' + moduleId + '</ns1:moduleId>' +
                   '<ns1:moduleVersion>' + moduleVersion + '</ns1:moduleVersion>' +
                   '</ns1:getPoliciesRequest>';

    var callURL = serverURL + "/" + MODULE_ADMIN_STRING;

    new wso2.wsf.WSRequest(callURL,"getPolicies",body_xml,getModulePoliciesCallback);
}

function getModulePoliciesCallback() {

    wso2.wsf.Util.callbackhelper(this.req.responseXML,"module_policies_edit.xsl", document.getElementById("divModules"));
    showlistPolicyModuleHeader(document.getElementById('modulePoliciesEditHeader'));
}

function updateModulePolicy(module_id, module_version, policy_value) {
    var body_xml = '<my:setPolicy xmlns:my="http://org.apache.axis2/xsd">' +
                   '<my:moduleId>' + module_id + '</my:moduleId>' +
                   '<my:moduleVersion>' + module_version + '</my:moduleVersion>' +
                   '<my:policyString><![CDATA[' + policy_value + ']]></my:policyString>' +
                   '</my:setPolicy>';

    var callURL = serverURL + "/" + MODULE_ADMIN_STRING;
    new wso2.wsf.WSRequest(callURL,"setPolicy",body_xml,updateModulePolicyCallback);
}

function updateModulePolicyCallback() {

    var restart = confirm("Module policy successfully updated." +
                          "\n The server needs to be restarted for the modified policy to take effect." +
                          "\n Restart now?");
    if (restart) {
        wso2.wsf.Util.restartServer();
    }
}

function getSequenceInfo(moduleId, moduleVersion) {

    lastUsedModuleId = moduleId;
    lastUsedModuleVersion = moduleVersion;

    var body_xml = '<my:getOutgoingSequenceData xmlns:my="http://org.apache.axis2/xsd">' +
                   '</my:getOutgoingSequenceData>';

    var callURL = serverURL + "/" + "Sandesha2Admin";
    new wso2.wsf.WSRequest(callURL,"urn:getOutgoingSequenceData",body_xml,getSequenceInfoCallback);

}

function getSequenceInfoCallback() {
    wso2.wsf.Util.callbackhelper(this.req.responseXML, "list_sandesha2_info.xsl", document.getElementById("divSandesha2Info"));
    showSandeshaModuleHeader(document.getElementById('sandesha2SequenceHeader'));
}
