/*
 * 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 retyped_pw_error = "Password and re-entered password do not match!";

var currentUserName;

function globalSecuritySettings(thisObj,index) {

    if (thisObj && index) {
        renderSelectedMenuItem(thisObj,index);
        gatherHistoryObject(thisObj.id, index);
    }
    
    var objDiv = document.getElementById("divUsers");

    var strHTML =  "<div style=\"align:left;\"><h2>Security Management</h2>"+
                   "<div id='formset'>"+
                   "<form>" +
                   "<fieldset>" +
                   "<legend>User and Role Management</legend>"+
                   "<h4><a href='#' onclick='manageRole(); return false;'><nobr/>Role Management</nobr></a></h4><p>Create new roles and edit existing roles.</p><p>&nbsp;</p>" +
                   "<h4><a href='#' onclick='manageUser(); return false;'><nobr>User Management</nobr></a></h4><p>Create new users, assign roles to users and edit existing users.</p>"+
                   "</fieldset>"+
                   "</form>"+
                   "</div></div>";

    objDiv.innerHTML = strHTML;
    wso2.wsf.Util.showOnlyOneMain(objDiv);
}
function manageUsers() {
    globalSecuritySettings();
}

function manageRole() {

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

    var callURL = serverURL + "/" + "UserAdmin" + "/" ;
    new wso2.wsf.WSRequest(callURL,"getRoleNamesAndDescriptions",body_xml,function(){
        wso2.wsf.Util.callbackhelper(this.req.responseXML,"role.xsl",document.getElementById("divManageRole"));
    });
}


function manageUser() {

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

    var callURL = serverURL + "/" + "UserAdmin" + "/" ;
    new wso2.wsf.WSRequest(callURL,"getUserNames",body_xml,function(){
        wso2.wsf.Util.callbackhelper(this.req.responseXML,"user.xsl", document.getElementById("divManageUser"));
    });
}

function editUsers(userName, userRole) {
    var strHTML1 =  "<h4><a href='#' onclick='javascript:manageUsers(); return false;'>Users</a>&nbsp;&gt;&nbsp;<a href='#' onclick='javascript:manageUser(); return false;'>User Management</a>&nbsp;&gt;&nbsp;Edit User</h4>" +
                  "<div id='formset'><form>";

    //regex for userName

    userName = userName.replace(/\xA7/g,"'"); // ASCII Value  \xA7 --> §

    currentUserName = userName;

    // Change role. We do not allow changing of role of the admin user
    var strHTML2 = (userName == 'admin')? "" :
                   "<fieldset>" +
                  "<legend>Assign role to user '" + userName + "'</legend>" +
                  "<div><label>User Role</label>" + "<select id='editUser_RoleCombo'></select></div>" +
                  "<div class='buttonrow'><input type='button' onclick='addUserWtihRole(document.getElementById(\"editUser_RoleCombo\"));' value='Assign'/></div>" +
                  "</fieldset>";

    // change password
    var strHTML3 = "<fieldset>" +
                  "<legend>Change password of user '" + userName + "'</legend>" +
                  "<div><label>Old Password<font color='red'>*</font></label>" + "<input type='password' id='editUser_old_password'/></div>" +
                  "<div><label>New Password<font color='red'>*</font></label>" + "<input type='password' id='editUser_password'/></div>" +
                  "<div><label>Re-enter New Password<font color='red'>*</font></label>" + "<input type='password' id='editUser_password_re'/></div>" +
                  "<div class='buttonrow'><input type='button' onclick='saveEditUserPw(document.getElementById(\"editUser_password\"), document.getElementById(\"editUser_password_re\"),document.getElementById(\"editUser_old_password\"));' value='Change Password'/></div>" +
                  "</fieldset>" +
                  "</form></div>";

    var strHTML = strHTML1 + strHTML2 + strHTML3;
    document.getElementById("divEditUser").innerHTML = strHTML;
    wso2.wsf.Util.showOnlyOneMain(document.getElementById("divEditUser"));

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

    var callURL = serverURL + "/" + "UserAdmin" + "/" ;
    var params = new Object();
    params["defaultRole"] = userRole;
    new wso2.wsf.WSRequest(callURL,"getRoleNames",body_xml,editUsersCallback,params);
}

function editUsersCallback() {

    var defaultRole = this.params["defaultRole"];
    var comboToLoad = document.getElementById('editUser_RoleCombo');
    if (comboToLoad != null) {
        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;
            if (rets[count].firstChild.nodeValue == defaultRole) {
                comboToLoad.options[count].selected = true;
            }
        }
    }
}
function saveEditUser(userNameObj, roleCombo) {

    var un = userNameObj.value;
    var roleName = roleCombo.value;
    var body_xml = '<req:editUserRoleRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   ' <req:username>' + un + '</req:username>\n' +
                   ' <req:role>' + roleName + '</req:role>\n' +
                   ' </req:editUserRoleRequest>\n';

    var callURL = serverURL + "/" + "UserAdmin" + "/" ;
    new wso2.wsf.WSRequest(callURL,"editUserRole",body_xml,saveEditUserCallback);

}

function saveEditUserPw(pw, pw_re, old_pw) {

    var un = currentUserName;
    var pwv = pw.value;
    if(old_pw.value == null || wso2.wsf.Util.trim(old_pw.value) == ""){
        wso2.wsf.Util.alertWarning("Old password cannot be empty");
        return false;
    }
    if (pwv  == null || wso2.wsf.Util.trim(pwv) == "") {
        wso2.wsf.Util.alertWarning('New Password cannot be Empty');
        return false;
    }
    var pw_rev = pw_re.value;
    if (wso2.wsf.Util.trim(pwv) != wso2.wsf.Util.trim(pw_rev)) {
        wso2.wsf.Util.alertWarning(retyped_pw_error);
        return false;
    }
    var body_xml = '<req:editUserPasswordRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   ' <req:oldPassword><![CDATA[' + (old_pw.value) + ']]></req:oldPassword>\n' +
                   ' <req:username><![CDATA[' + un + ']]></req:username>\n' +
                   ' <req:password><![CDATA[' + pwv + ']]></req:password>\n' +
                   ' </req:editUserPasswordRequest>\n';

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

function saveEditUserCallback() {

    var data = this.req.responseXML;

    if (data.getElementsByTagName("return")[0].firstChild.nodeValue == "true") {
        wso2.wsf.Util.alertMessage("Editing user was successful.");
    }
    manageUser();
}

function saveEditUserPwCallback() {

    var data = this.req.responseXML;

    if (data.getElementsByTagName("return")[0].firstChild.nodeValue == "true") {
        wso2.wsf.Util.alertMessage("Update password was successful.");
        manageUser();
    } else {
        wso2.wsf.Util.alertWarning("Password update failed. Please recheck your old password.");
    }
}

//add user - used in user management
function addUser(userName, password, password_re, role, description) {
    var un = userName.value;
    var pw = password.value;
    var dp = description.value;
    if(un == null || wso2.wsf.Util.trim(un) == ""){
        wso2.wsf.Util.alertWarning("Please enter a valid username.");
        return false;
    }
    if(pw == null || wso2.wsf.Util.trim(pw) == ""){
        wso2.wsf.Util.alertWarning("Please enter the password.");
        return false;
    }

    var pw_re = password_re.value;
    if (pw != pw_re) {
        wso2.wsf.Util.alertWarning(retyped_pw_error);
        return false;
    }
    var rl = role[role.selectedIndex].value;

    if(dp == null || wso2.wsf.Util.trim(dp) == ""){
        dp = "";
    }
    var body_xml = '<req:addUserRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   ' <req:username><![CDATA[' + un + ']]></req:username>\n' +
                   ' <req:password><![CDATA[' + pw + ']]></req:password>\n' +
                   ' <req:role><![CDATA[' + rl + ']]></req:role>\n' +
                   ' <req:description><![CDATA[' + dp + ']]></req:description>\n' +
                   ' </req:addUserRequest>\n';

    var callURL = serverURL + "/" + "UserAdmin" + "/" ;
    role.value = "";
    password.value = "";
    password_re.value = "";
    role.value = "";
    new wso2.wsf.WSRequest(callURL,"addUser",body_xml,addUserCallback);
}

function addUserCallback() {

    wso2.wsf.Util.showResponseMessage(this.req.responseXML);
    manageUser();
}

function addRoleCallBack() {

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

    if (text.firstChild.nodeValue == 'true'){
        wso2.wsf.Util.alertMessage("User role was added successfully.");
    }else {
        wso2.wsf.Util.alertWarning("User role already exists.");
    }
    manageRole();
}

function addRole(role,description) {
    var rolename = role.value;
    var roleDescription = description.value;
    if(rolename == null || wso2.wsf.Util.trim(rolename) == ""){
        wso2.wsf.Util.alertWarning("Please enter a valid Role name.");
        return false;
    }
    if(roleDescription == null || wso2.wsf.Util.trim(roleDescription) == ""){
        roleDescription = "";
    }
    if (wso2.wsf.Util.trim(rolename) != '') {
        var xsltFileName = "role.xsl";
        var body_xml = '<req:addRoleRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                       ' <req:role><![CDATA[' + rolename + ']]></req:role>\n' +
                       ' <req:description><![CDATA[' + roleDescription + ']]></req:description>\n' +
                       ' </req:addRoleRequest>\n';

        var callURL = serverURL + "/" + "UserAdmin" + "/" ;
        role.value = "";
        //TODO do a proper QA
//        send("addRole", body_xml, xsltFileName, callURL, document.getElementById("divAddRole"), false, addRoleCallBack);
        new wso2.wsf.WSRequest(callURL,"addRole",body_xml,addRoleCallBack);
    } else {
        wso2.wsf.Util.alertWarning("Please specify the user role to add.");
    }

    //refresh page
    //manageRole();
}

// loading the user names for the combo
function loadUserListComboBox() {
    var body_xml = '<req:getRoleNamesRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   ' </req:getRoleNamesRequest>\n';

    var callURL = serverURL + "/" + "UserAdmin" + "/" ;
    new wso2.wsf.WSRequest(callURL,"getRoleNames",body_xml,loadUserListCallback);

}

//load user list callback.
function loadUserListCallback() {

    var comboToLoad = document.getElementById('roleSelectBox');
    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;
    }

}
function loadUsersComboBox() {
    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,"getUsers",body_xml,loadUsersCallback);
}

function loadUsersCallback() {

    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;
    }
}

function deleteUser(user) {

    user = user.replace(/\xA7/g,"'");

    if (user == 'admin') {
        wso2.wsf.Util.alertWarning("You cannot delete the default admin account!");
        return false;
    }
    var deleteIt= confirm("Do you really want to delete user "+ user +"?");
    if (deleteIt) {
        var body_xml = '<req:deleteUserRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                       '<req:deleteUser><![CDATA[' + user + ']]></req:deleteUser>\n'+
                       '</req:deleteUserRequest>\n';

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

function deleteUserCallback() {

    wso2.wsf.Util.alertMessage("User was deleted successfully.");
    manageUser();
}

function deleteRole(user,role) {

    user = user.replace(/\xA7/g,"'");
    role = role.replace(/\xA7/g,"'");

    if (user == 'admin') {
        wso2.wsf.Util.alertWarning("You cannot modify the default admin account settings!");
        return false;
    }
    var deleteIt= confirm("Do you really want to unassign role "+ role +" from user " + user + "?");
    if (deleteIt) {
        var body_xml = '<req:deleteRoleFromUserRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                       '<req:username><![CDATA[' + user + ']]></req:username>\n'+
                       '<req:role><![CDATA[' + role + ']]></req:role>\n'+
                       '</req:deleteRoleFromUserRequest>\n';

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

function deleteRoleCallback() {

    var data = this.req.responseXML;

    if (data.getElementsByTagName("return")[0].firstChild.nodeValue == "true") {
        wso2.wsf.Util.alertMessage("Unassigned user from role successfully.");
    } else {
        wso2.wsf.Util.alertWarning("Role Cannot be removed since a user should have at least one role.<br/>" +
                    "Please assign another role to this user before trying removing this role.");
    }
    manageUser();
}

function addUserWtihRole(role) {

    if (currentUserName == 'admin') {
        wso2.wsf.Util.alertWarning("You cannot modify the default admin account settings!");
        return false;
    }


    rl = role[role.selectedIndex].value;

    var body_xml = '<req:assignRoleToUser xmlns:req="http://org.apache.axis2/xsd">\n' +
                   '<req:username><![CDATA[' + currentUserName + ']]></req:username>\n'+
                   '<req:role><![CDATA[' + rl + ']]></req:role>\n'+
                   '</req:assignRoleToUser>\n';

    var callURL = serverURL + "/" + "UserAdmin" + "/" ;
    new wso2.wsf.WSRequest(callURL,"assignRoleToUser",body_xml,addUserWtihRoleCallback);

}

function addUserWtihRoleCallback() {

    wso2.wsf.Util.alertMessage("Role successfully assigned to user");
    manageUser();
}

function deleteRoleCompletely(role) {
    role = role.replace(/\xA7/g,"'");

    if (role == 'admin') {
        wso2.wsf.Util.alertWarning("You cannot delete the default admin role!");
        return false;
    }
    var deleteIt= confirm("Do you really want to delete role "+ role +"?");
    if (deleteIt) {
        var body_xml = '<req:deleteRoleCompletelyRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                       '<req:role><![CDATA[' + role + ']]></req:role>\n'+
                       '</req:deleteRoleCompletelyRequest>\n';

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

function deleteRoleCompletelyCallback() {

    var data = this.req.responseXML;

    var deleteStatement = data.getElementsByTagName("return")[0].firstChild.nodeValue;
    wso2.wsf.Util.alertMessage(deleteStatement);

    manageRole();

}

