/*
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 assign tester form submit button */
$("#buttonAssignTester").click(function() {
    sendTester(getSelectedUsers(".testerSelector"));
    $('#modal-tester-assignment').modal('hide');
});

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

    return tester;
}

/**
 * @param testers
 *
 * Shows all new assigned users in the "Testers" menu
 */
function sendTester(testers) {
    var urlSeg = window.location.pathname.split("/");
    url = urlSeg[0] + "/" + urlSeg[1] + "/" + urlSeg[2] + "/" + urlSeg[3] + "/" + urlSeg[4] + "/tester";

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

    /* Alerts the results */
    posting.done(function (response) {
       // show Notification with success message
        var testerContainer = $("#testerContainer");
        testerContainer.empty();

        if(testers.length < 1) {
            testerContainer.append("<span class=\"text-muted\">No assigned testers</span>");
        }else{
            var list = document.createElement("ul");
            testerContainer.append(list);
        }

        testers.forEach(function (elem) {
            var li = document.createElement("li");
            li.appendChild(document.createTextNode(elem));
            list.append(li);
        });

    }).fail(function (response) {
        $("#modalPlaceholder").empty().append(response.responseText);
        $('#errorModal').modal('show');
    });
}

