/*
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"), getRoles(), true);
    $('#modal-member-assignment').modal('hide');
});

/* attach a handler to the remove member form submit button */
$("#buttonRemoveMember").click(function () {
    sendMembers(getSelectedUsers(".removeMemberSelector"), null, 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;
}

function getRoles() {
    var roles = [];
    $(".roleSelector").each(function () {
        roles.push(this.value);
    });
    return roles;
}

/* sends ajax message with the new/soon-to-be removed members to server */
function sendMembers(members, roles, 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),
                roles: JSON.stringify(roles)
            }
        });

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

function roleSelection(member, id, index) {
    var path = currentURL().toString() + "/update";
    //get selected of dropdown
    var selectedRole = document.getElementById(id).options[index].value;
    //update role from user with selectedRole
    var posting = $.ajax({
        url: path,
        type: "PATCH",
        data: {
            member: JSON.stringify(member),
            role: JSON.stringify(selectedRole)
        }
    });
    posting.done(function (response) {
        location.replace(location.pathname);
        return true;
    }).fail(function (response) {
        $("#modalPlaceholder").empty().append(response.responseText);
        $("#errorModal").modal("show");

        var selectObj = document.getElementById(id);
        //Set selected
        var valueToSet = "Supervisor";
        for (var i = 0; i < selectObj.options.length; i++) {
            if (selectObj.options[i].text === valueToSet) {
                selectObj.options[i].selected = true;
                return;
            }
        }
    });
}