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

/*
crypto.js handles CryptoAdmin related Adminstration
*/

var CRYPTO_ADMIN = "CryptoAdmin";

var KEYSTORE_FOR_TRANSPORT;

var KEYSTORENAME_FOR_CERTIFICATE;

function getAllkeystoreNames() {
    var body_xml = '<ns1:getAllKeyStoreNamesRequest xmlns:ns1="http://org.apache.axis2/xsd">' +
                   '</ns1:getAllKeyStoreNamesRequest>';

    var callURL = serverURL + "/" + CRYPTO_ADMIN + "/" + "getAllKeyStoreNames";
    new wso2.wsf.WSRequest(callURL,"getAllKeyStoreNames",body_xml,getAllkeystoreNamesCallback);
}

function getAllkeystoreNamesCallback() {
    var data = this.req.responseXML;
    var returnStores = data.getElementsByTagName("return");

    if (returnStores.length == 1) {
        //do for only one
        KEYSTORE_FOR_TRANSPORT =
        data.getElementsByTagName("return")[0].firstChild.nodeValue;
        transportWizardStatus();
    } else {
        // for more
        wso2.wsf.Util.callbackhelper(this.req.responseXML,"list_keystore_props.xsl", document.getElementById("divAddListKeyStores"));
    }
}


function getPrivateKeys() {
    var body_xml = '<ns1:getPrivateKeysRequest xmlns:ns1="http://org.apache.axis2/xsd">' +
                   '<keyStoreFileId>' + KEYSTORE_UUID + '</keyStoreFileId>' +
                   '<storePass><![CDATA[' + KEYSTORE_PASSWORD + ']]></storePass>' +
                   '<keyStoreType>' + KEYSTORE_TYPE + '</keyStoreType>' +
                   '</ns1:getPrivateKeysRequest>';

    var callURL = serverURL + "/" + CRYPTO_ADMIN + "/" + "getPrivateKeys";
    new wso2.wsf.WSRequest(callURL,"getPrivateKeys",body_xml,getPrivateKeysCallback);

}

function getPrivateKeysCallback() {
        // if statement for check if there are 1 or more private keys
    var data = this.req.responseXML;
    var privateKeys = data.getElementsByTagName("return");

    if (privateKeys.length == 1) {
        ONLY_ONE_ALIAS = true;
        PRIVATE_KEY_ALIASE = data.getElementsByTagName("return")[0].firstChild.nodeValue;
        privateKeyPassword(data.getElementsByTagName("return")[0].firstChild.nodeValue);
        // Note: from keystore.js
    } else {
//        alert('xml   ' + xmlSerializerToString(data))
        var xslAbsPath = URL + "/extensions/core/xslt/list_keystore_props.xsl";
        var xsltHelperObj = new wso2.wsf.XSLTHelper();
        var divObject = document.getElementById("divListPrivetKeys");
        xsltHelperObj.transform(divObject, this.req.responseXML, xslAbsPath, true);
        wso2.wsf.Util.showOnlyOneMain(divObject);
    }

}

function addNewKeyStore() {

    var body_xml = '<ns1:addNewKeyStoreRequest xmlns:ns1="http://org.apache.axis2/xsd">' +
                   '<ksFilePathId>'+ KEYSTORE_UUID+'</ksFilePathId>'+
                   '<ksPassword><![CDATA['+ KEYSTORE_PASSWORD+ ']]></ksPassword>'+
                   '<pvtKeyAlias><![CDATA['+ PRIVATE_KEY_ALIASE +']]></pvtKeyAlias>'+
                   '<pvtKeyPassword><![CDATA[' + PRIVATE_KEY_PASSWORD + ']]></pvtKeyPassword>'+
                   '<keyStoreType>'+ KEYSTORE_TYPE+'</keyStoreType>'+
                   '<provider>' + PROVIDER + '</provider>'+
                   '</ns1:addNewKeyStoreRequest>';

    var callURL = serverURL + "/" + CRYPTO_ADMIN + "/" + "addNewKeyStore";
    new wso2.wsf.WSRequest(callURL,"addNewKeyStore",body_xml,addNewKeyStoreCallback);

}

function addNewKeyStoreCallback() {

    var data = this.req.responseXML;

    var returnDatum = data.getElementsByTagName("return")[0].firstChild.nodeValue;

    finalizeKeystoreWizard(returnDatum);


}

function showImportCertificate(keystoreName) {

    KEYSTORENAME_FOR_CERTIFICATE = keystoreName;

    var objDiv = document.getElementById("divImportCertificate");

    var strHTML =     "<h4><a href='#' onClick='javascript:keystoreSetting(); return false;'>Keystores</a>&nbsp;&gt;&nbsp;Import Certificate</h4>"+
                      "<fieldset style='border:none;'>" +
                      "<div id='formset'>" +
                      "<form method='post' name='certificateupload' action='fileupload/certificate' enctype='multipart/form-data' target='globalIFrame'>" +
                      "<fieldset>" +
                      "<legend>Import Certificate</legend>" +
                      "<div><label>Certificate<font color='red'>*</font>"+
                      "</label><input type='file' name='certificateFile' id='certificateFile' size='50'/></div>" +
                      "<br/>"+
                      "<div class='buttonrow'>" +
                      "<input type=\"submit\" onclick=\"return validateimportCertificate();\" value=\"Upload\"/>" +
                      "</div>" +
                      "</fieldset>" +
                      "</form>" +
                      "<form>"+
                      "<fieldset>" +
                      "<legend>Available Certificates</legend>" +
                      "<div id='importedCertificatesDivId' />"+
                      "</fieldset>"+
                      "</form>"+
                      "</div>" +
                      "</fieldset>";

        objDiv.innerHTML = strHTML;
        wso2.wsf.Util.showOnlyOneMain(objDiv);
        // show imported certificates
        getCertificates();

}

function getCertificates() {
    var body_xml = '<ns1:getCertificates xmlns:ns1="http://org.apache.axis2/xsd">' +
                   '<keyStoreName>'+KEYSTORENAME_FOR_CERTIFICATE+'</keyStoreName>'+
                   '</ns1:getCertificates>';

    var callURL = serverURL + "/" + CRYPTO_ADMIN + "/" + "getCertificates";
    new wso2.wsf.WSRequest(callURL,"getCertificates",body_xml,getCertificatesCallback);

}

function getCertificatesCallback() {

    transformationWithoutHistory(this.req.responseXML,"list_imported_certificates.xsl", document.getElementById("importedCertificatesDivId"));

}

function validateimportCertificate() {
    if (wso2.wsf.Util.trim(document.certificateupload.certificateFile.value) == "") {
        wso2.wsf.Util.alertWarning("Please select a certificate file.");
        return false;
    }
    /*setting the callback method*/
    FileExcutor.execute = certificateFileUpload;
    return true;
}

function certificateFileUpload(uuid) {

    var body_xml = '<ns1:importCertificate xmlns:ns1="http://org.apache.axis2/xsd">' +
                   '<keyStoreName>' + KEYSTORENAME_FOR_CERTIFICATE + '</keyStoreName>' +
                   '<certificatePathId>' + uuid + '</certificatePathId>' +
                   '</ns1:importCertificate>';

    var callURL = serverURL + "/" + CRYPTO_ADMIN + "/" +"importCertificate";
    new wso2.wsf.WSRequest(callURL,"importCertificate",body_xml,certificateFileUploadCallback);

}

function certificateFileUploadCallback() {

    var data = this.req.responseXML;
    var returnStatus = data.getElementsByTagName("return")[0].firstChild.nodeValue;

    wso2.wsf.Util.alertMessage(returnStatus);
    //calling the main
    keystoreSetting();

}

function getKeystoreInfo(keyStoreName) {
    var bodyXML = '<ns1:getKeystoreInfo xmlns:ns1="http://org.apache.axis2/xsd">' +
                  '<keyStoreName>' + keyStoreName + '</keyStoreName>' +
                  '</ns1:getKeystoreInfo>';

    var callURL = serverURL + "/" + CRYPTO_ADMIN;
    new wso2.wsf.WSRequest(callURL, "urn:getKeystoreInfo", bodyXML, getKeystoreInfoCallback);

}

function getKeystoreInfoCallback() {
   wso2.wsf.Util.callbackhelper(this.req.responseXML,"keystores.xsl", document.getElementById("divKeyStoreExplor"));
}


