/*
This file is part of SystemTestPortal.
Copyright (C) 2017  Institute of Software Technology, University of Stuttgart

SystemTestPortal is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

SystemTestPortal is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with SystemTestPortal.  If not, see <http://www.gnu.org/licenses/>.
*/

/* attach a handler to the add member form submit button */
$("#buttonAssignMember").click(function() {
    sendMembers(getSelectedUsers(".memberSelector"), true);
    $('#modal-member-assignment').modal('hide');
});

/* attach a handler to the remove member form submit button */
$("#buttonRemoveMember").click(function() {
    sendMembers(getSelectedUsers(".removeMemberSelector"), false);
    $('#modal-member-remove').modal('hide');
});

/* fetches the selected users from checkboxes */
function getSelectedUsers(selector) {
    var members = [];
    $(selector).each(function () {
        if(this.checked) {
            members.push(this.name);
        }
    });
    return members;
}

/* sends ajax message with the new/soon-to-be removed members to server */
function sendMembers(members, add) {
    var urlSeg = window.location.pathname.split("/");
    if(add) { //add members
        target = urlSeg[0] + "/" + urlSeg[1] + "/" + urlSeg[2] + "/" + urlSeg[3] + "/add";

        var posting = $.ajax({
            url: target,
            type: "PUT",
            data: { members: JSON.stringify(members) }
        });

    } else { //remove members
        target = urlSeg[0] + "/" + urlSeg[1] + "/" + urlSeg[2] + "/" + urlSeg[3] + "/remove";

        var posting = $.ajax({
            url: target + "?" + $.param({"members": JSON.stringify(members)}),
            type: "DELETE"
        });
    }

    /* Alerts the results */
    posting.done(function (response) {
        // show Notification with success message
        location.reload();
    }).fail(function (response) {
        $("#modalPlaceholder").empty().append(response.responseText);
        $('#errorModal').modal('show');
    });
}