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

/*
Service Group manipulation
*/

var moduleServiceGroupName;

/**
 * Intialize the service group with the given name.
 */
function showServiceGroupInfo(serviceGroupName) {
    /* stopping the refreshing first when the system running in very latent systems */
    stoppingRefreshingMethodsHook();

    moduleServiceGroupName = serviceGroupName;
    var body_xml = '<req:listServiceGroup xmlns:req="http://org.apache.axis2/xsd">' +
                   '<serviceGroupName>' + serviceGroupName + '</serviceGroupName>' +
                   '</req:listServiceGroup>';

    var callURL = serverURL + "/" + SERVICE_GROUP_ADMIN_STRING + "/" ;
    new wso2.wsf.WSRequest(callURL, "urn:listServiceGroup", body_xml, showServiceGroupInfoCallback);

}

/**
 * configureMTOM
 */
function configureMTOM(flag,serviceGroupName) {
    var body_xml = '<req:configureMTOM xmlns:req="http://org.apache.axis2/xsd">' +
                   '<flag>' + flag + '</flag>' +
                   '<serviceGroupName>' + serviceGroupName + '</serviceGroupName>' +
                   '</req:configureMTOM>';

    var callURL = serverURL + "/" + SERVICE_GROUP_ADMIN_STRING + "/" ;
    new wso2.wsf.WSRequest(callURL, "urn:configureMTOM", body_xml, showServiceGroupInfoCallback);

}

function showServiceGroupInfoCallback() {
    wso2.wsf.Util.callbackhelper(this.req.responseXML, "list_servicegroup_main_info.xsl", document.getElementById('divshowServiceGroupInfo'));

}

function getServiceGroupSpecificParametersForConfig(serviceGroupId) {
    if (serviceGroupId == null) { // this happend only when call made within to this service
        serviceGroupId = moduleServiceGroupName;

    } else {
        moduleServiceGroupName = serviceGroupId;
    }
    var body_xml = '<req:getDeclaredServiceGroupParametersRequest xmlns:req="http://org.apache.axis2/xsd">' +
                   '<serviceGroupId>' + serviceGroupId + '</serviceGroupId>' +
                   '</req:getDeclaredServiceGroupParametersRequest>';

    var callURL = serverURL + "/" + SERVICE_GROUP_ADMIN_STRING + "/" ;
    new wso2.wsf.WSRequest(callURL,"getDeclaredServiceGroupParameters",body_xml,getServiceGroupSpecificParametersForConfigCallback);
}

function getServiceGroupSpecificParametersForConfigCallback() {

    wso2.wsf.Util.callbackhelper(this.req.responseXML,"list_service_group_params_edit.xsl", document.getElementById("divGetServiceGroupSpecficParameters"));
    showlistServiceGroupParamHeader(document.getElementById('listServiceGroupParamEditHeader'));

}

function addServiceGroupParameter() {
    var newParam = wso2.wsf.Util.getUserInput();
    if (newParam != null) {
        processSingleOperationParameterConfigEntrySG(moduleServiceGroupName,
                newParam[0],
                newParam[1], getServiceGroupSpecificParametersForConfig);
    }

}
function removeServiceGroupParameter(button) {
        processSingleOperationParameterConfigEntrySGRemoval(moduleServiceGroupName,
                button.id, getServiceGroupSpecificParametersForConfig);
    

}
function processSingleOperationParameterConfigEntrySGRemoval(serviceGroupName, parameterName,
		 callback) {

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


    var body_xml = '<ns1:removeServiceGroupParameterRequest xmlns:ns1="http://org.apache.axis2/xsd">' +
                   '<serviceGroupId>' + serviceGroupName + '</serviceGroupId>' +
                   '<parameter locked="false" name="' + parameterName + '"></parameter>' +
                   '</ns1:removeServiceGroupParameterRequest>';

    var callURL = serverURL + "/" + SERVICE_GROUP_ADMIN_STRING;
    //update the information in operation display page
    updateServiceGroupOperationInfoDisplay("Sending value for " + parameterName);
    new wso2.wsf.WSRequest(callURL,"removeServiceGroupParameter",body_xml,callback);

}

function processMultipleOperationParameterConfigEntrySG(serviceGroupName, parameterNamesObj,
                                                      parameterValueObj){
    // the length of  parameterNamesObj and  parameterValueObj are same

    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:setServiceGroupParameters xmlns:ns1="http://org.apache.axis2/xsd">\n' +
                   '<serviceGroupId>' + serviceGroupName + '</serviceGroupId>\n' +
                   paramElements +
                   '</ns1:setServiceGroupParameters>';

    var callURL = serverURL + "/" + SERVICE_GROUP_ADMIN_STRING;
    new wso2.wsf.WSRequest(callURL,"setServiceGroupParameters",body_xml,processMultipleOperationParameterConfigEntrySGCallback);


}

function processMultipleOperationParameterConfigEntrySGCallback() {

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

    getServiceGroupSpecificParametersForConfig(moduleServiceGroupName);



}
function processSingleOperationParameterConfigEntrySG(serviceGroupName, parameterName,
                                                      parameterValue, callback) {

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


    var body_xml = '<ns1:setServiceGroupParameterRequest xmlns:ns1="http://org.apache.axis2/xsd">' +
                   '<serviceGroupId>' + serviceGroupName + '</serviceGroupId>' +
                   '<parameter locked="false" name="' + parameterName + '"><![CDATA[' + parameterValue +
                   ']]></parameter>' +
                   '</ns1:setServiceGroupParameterRequest>';

    var callURL = serverURL + "/" + SERVICE_GROUP_ADMIN_STRING;
    //update the information in operation display page
    updateServiceGroupOperationInfoDisplay("Sending value for " + parameterName);
    new wso2.wsf.WSRequest(callURL,"setServiceGroupParameter",body_xml,callback);

}
/*
arrayOfName and arrayOfvalues have one to one
*/
function processServiceGroupParameterConfigUpdate(arrayOfNames, arrayOfValues) {

    processMultipleOperationParameterConfigEntrySG(
            moduleServiceGroupName,
            arrayOfNames,
            arrayOfValues);
}

function updateServiceGroupOperationInfoDisplay(message) {
    document.getElementById('serviceGroupParamUpdate').innerHTML = message;
}

// Module Management


function engageModulePerServiceGroup(serviceGroupId) {
    moduleServiceGroupName = serviceGroupId;

    var objDiv = document.getElementById("divEngageModuleForServiceGroup");
    var strInnerHtml = "<h4><a href='#' onClick='javascript:showServiceInitializer(); return false;'>Services</a>&nbsp;&gt;&nbsp;<a href='#' onClick='javascript:showServiceGroupInfo(\"" + serviceGroupId + "\"); return false;'>" + "ServiceGroup[" +serviceGroupId +"]"+ "</a>&nbsp;&gt;&nbsp;Engage Modules</h4>" +
                  "<fieldset style='border: none;'>" +
                  "<div id='formset'>" +
                  "<form>" +
                  "<fieldset>" +
                  "<legend>Engage module to Service Group <font color='blue'>" + serviceGroupId + "</font></legend>" +
                  "<div><label>Module</label><span id='engageModulePerServiceGroupCombo'></span></div>" +
                  "<div class='buttonrow'><input type='button' onclick='javascript:engageModulePerServiceGroupExec(\"" + serviceGroupId + "\", document.getElementById(\"cmbEngageModulePerServiceGroupCombo\").value);' value='Engage'/></div>" +
                  "</fieldset>" +
                  "</form>" +
                  "<div id='modulesEngageOnServiceGroup' style='display:inline; position: relative; top: 20px;'></div>" +
                  "<div id='globleModulesOnServiceGroup' style='display:inline; position: relative; top: 20px;'></div>" +
                  "</div>" +
                  "</fieldset>";


    objDiv.innerHTML = strInnerHtml;
    wso2.wsf.Util.showOnlyOneMain(objDiv);

    //globally engage

    body_xml = '<req:listGloballyEngagesModulesRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
               ' </req:listGloballyEngagesModulesRequest>\n';
    callURL = serverURL + "/" + "ModuleAdmin" + "/" ;
    new wso2.wsf.WSRequest(callURL,"listGloballyEngagesModules",body_xml,globallyEngageModulesOnServiceGroupCallback);

}

function globallyEngageModulesOnServiceGroupCallback() {

    var xsltFileName = "list_engaged_modules_per_service.xsl";
    var objDiv = document.getElementById("globleModulesOnServiceGroup");
    var data = this.req.responseXML;
    wso2.wsf.Util.processXML(data, xsltFileName, objDiv);

    //listing for  modulesEngageOnServiceGroup
    var body_xml = '<req:listServiceGroupModulesRequest xmlns:req="http://org.apache.axis2/xsd">' +
                   ' <serviceGroupId>' + moduleServiceGroupName + '</serviceGroupId>' +
                   ' </req:listServiceGroupModulesRequest>';

    var callURL = serverURL + "/" + "ModuleAdmin" + "/" ;
    new wso2.wsf.WSRequest(callURL,"listServiceGroupModules",body_xml,listServiceGroupModulesCallback);

}

function listServiceGroupModulesCallback() {

    var xsltFileName = "list_engaged_modules_per_service.xsl";
    var objDiv = document.getElementById("modulesEngageOnServiceGroup");
    var data = this.req.responseXML;
    wso2.wsf.Util.processXML(data, xsltFileName, objDiv);

    //listing the engageModulePerServiceGroupCombo

    getGlobalModuleComboServiceGroup(document.getElementById("engageModulePerServiceGroupCombo"), "cmbEngageModulePerServiceGroupCombo");


}


function getGlobalModuleComboServiceGroup(cmbSpan, cmbName) {
    moduleSpanToUse = cmbSpan;
    moduleComboName = cmbName;
//    alert("Global module getting function called");

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

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

}

function getGlobalModuleComboServiceGroupCallback() {

    var data = this.req.responseXML;

//    alert("XSL = " + (new XMLSerializer()).serializeToString(data));

    var strHTML = "<select id='" + moduleComboName + "'>";
    var rets = data.getElementsByTagName("return");
    var len = rets.length;
    var count;
    var moduleVersion;
    for (count = 0; count < len; count++) {
    	if (rets[count].getElementsByTagName("moduleVersion")[0].firstChild != null){
    		moduleVersion = rets[count].getElementsByTagName("moduleVersion")[0].firstChild.nodeValue;
    	} else {
    		moduleVersion = "";
    	}
        displayModuleVersion = (moduleVersion == "" ? "" : ("-"+moduleVersion));
        strHTML += "<option value='" + rets[count].getElementsByTagName("moduleId")[0].firstChild.nodeValue + '||' + moduleVersion + "'>" + rets[count].getElementsByTagName("modulename")[0].firstChild.nodeValue +displayModuleVersion+ "</option>\n";
    }
    strHTML += "</select>"

    moduleSpanToUse.innerHTML = strHTML;

}

function engageModulePerServiceGroupExec(serviceGroupId, moduleName) {
    var moduleVersion = moduleName.substring(moduleName.indexOf('||') + 2, moduleName.length);
    moduleServiceGroupName = serviceGroupId;
    setModuleVersion = moduleVersion;
    moduleName = moduleName.substring(0, moduleName.indexOf('||'));
    //	alert("engageModulePerServiceExec Called with serviceName = " +serviceName + " || moduleName = " + moduleName + " ||| moduleVersion = " + moduleVersion);
    setModuleName = moduleName;

    var body_xml = '<req:engageModuleForServiceGroupRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   ' <moduleId>' + moduleName + '</moduleId>\n' +
                   ' <moduleVersion>' + moduleVersion + '</moduleVersion>\n' +
                   ' <serviceGroupId>' + serviceGroupId + '</serviceGroupId>\n' +
                   ' </req:engageModuleForServiceGroupRequest>\n';

    var callURL = serverURL + "/" + "ModuleAdmin" + "/" ;
    new wso2.wsf.WSRequest(callURL,"engageModuleForServiceGroup",body_xml,engageModulePerServiceGroupExecCallback);

}

function engageModulePerServiceGroupExecCallback() {

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

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

    setTimeout(function() {engageModulePerServiceGroup(moduleServiceGroupName);},1000);

}

function disengageModuelfromServiceGroupExec(moduleName, moduleVersion) {
    var body_xml = '<req:disengageModuleFromServiceGroupRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   '<moduleId>' + moduleName + '</moduleId>\n' +
                   '<moduleVersion>' + moduleVersion + '</moduleVersion>\n' +
                   '<serviceGroupId>' + moduleServiceGroupName + '</serviceGroupId>\n' +
                   '</req:disengageModuleFromServiceGroupRequest>\n';

    var callURL = serverURL + "/" + "ModuleAdmin" + "/" ;
    new wso2.wsf.WSRequest(callURL,"disengageModuleFromServiceGroup",body_xml,disengageModuelfromServiceGroupExecCallback);

}

function disengageModuelfromServiceGroupExecCallback() {

    wso2.wsf.Util.alertMessage("Module was disengaged from service successfully.");
    setTimeout(function() {engageModulePerServiceGroup(moduleServiceGroupName);},1000);

}

function dumpAAR(serviceGroupName) {

    var body_xml = '<req:dumpAAR xmlns:req="http://org.apache.axis2/xsd">\n' +
                   '<serviceGroupName>' + serviceGroupName + '</serviceGroupName>\n' +
                   '</req:dumpAAR>\n';

    var callURL = serverURL + "/" + SERVICE_GROUP_ADMIN_STRING ;
    new wso2.wsf.WSRequest(callURL,"dumpAAR",body_xml,generateCallBack);

}
