/*
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").off('click').on('click', function () {
    sendMembers(getSelectedUsers(".memberSelector"), getRoles(), true);
    $('#modal-member-assignment').modal('hide');
});

/* attach a handler to the remove member form submit button */
$("#buttonRemoveMember").off('click').on('click', function () {
    var selectedUsers = getSelectedUsers(".removeMemberSelector");

    if(isDangerousRemove(selectedUsers)) {
        $('#modal-member-remove').modal('hide');
        $('#remove-abort-modal').modal('show');
    } else {

        sendMembers(selectedUsers, null, false);

        $('#modal-member-remove').modal('hide');
    }
});

/* Button remove confirm sends the removal request even though users have assignments */
$("#buttonRemoveConfirm").off('click').on('click', function() {
    var selectedUsers = getSelectedUsers(".removeMemberSelector");

    sendMembers(selectedUsers, null, false);

    $('#remove-abort-modal').modal('hide');
    $('#modal-member-remove').modal('hide');
});

/* Button cancel remove sends the user back to the selection modal */
$("#buttonRemoveCancel").off('click').on('click', function() {
    $('#modal-member-remove').modal('show');
    $('#remove-abort-modal').modal('hide');
});

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

function getRoles() {
    const 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) {
    const urlSeg = window.location.pathname.split("/");
    let posting;
    if (add) { //add members
        target = urlSeg[0] + "/" + urlSeg[1] + "/" + urlSeg[2] + "/" + urlSeg[3] + "/add";

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

        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) {
    const path = currentURL().toString() + "/update";
    //get selected of dropdown
    const selectedRole = document.getElementById(id).options[index].value;
    //update role from user with selectedRole
    const 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");

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

/**
 * Checks if the selected members contain dangerous users
 * @param members
 * @returns {boolean}
 */
function isDangerousRemove(members) {
    for (i = 0; i < members.length; i++) {
        if (dangerousMembers.includes(members[i])) {
            return true;
        }
    }

    return false;
}


/**
 * Checks and marks dangerous members
 */
$(function () {
    for (let i = 0; i < dangerousMembers.length; i++){
        const input = document.getElementById(dangerousMembers[i]);
        const $label = $("label[for='" + input.id +  "']");
        $label.css('color', 'red');
    }
});