/*
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/>.
*/

$.getScript("/static/js/util/common.js");


/* (Button) Handler */
// attach a handler to the add test cases form submit button
$("#buttonAddTestCases").click(function() {
    var testcases = "";
    $(".testCaseInTestSequence").each(function () {
        testcases = testcases + this.id + "/";
    });
    $(".testCaseSelector").each(function () {
        if(this.checked) {
            if(document.getElementById("testCaseListPlaceholder")) {
                $("#testCaseListPlaceholder").remove();
            }
            $( "#testCasesList" ).append(createListItem(this.id, this.name));
            testcases = testcases + this.id + "/";
        }
    });

    $('#modal-testcase-selection').modal('hide');
    refreshTestsequence(testcases);
    reloadDragAndDropFeature();
});

// returns a new list item
function createListItem(id, name){

    return $(`<li class="list-group-item testCaseInTestSequence" id="${id}">
                <button type="button" class="test-sequence-reorder">
                    <i class="fa fa-bars"></i>
                </button>
                <span>${name}</span>
                <button type="button" class="remove-test-case close" aria-label="Remove">
                    <span aria-hidden="true">&times;</span>
                </button>
            </li>`);
}

// Add Remove-Handler
$(document).on('click', '.remove-test-case', function() {
    if($(this).parent().parent().children().length < 2) {
        $(this).parent().parent().append("" +
            "<li class=\"list-group-item\" id=\"testCaseListPlaceholder\">" +
            "   <span class=\"text-muted\">No Test Cases</span>" +
            "   <button type=\"button\" class=\"add-test-case close ml-auto\" aria-label=\"Add Test Case\" " +
            "           data-toggle=\"modal\" data-target=\"#modal-testcase-selection\">" +
            "       <span aria-hidden=\"true\">+</span>" +
            "   </button>" +
            "</li>");
    }
    $(this).parent().remove();

    var testcases = "";
    $(".testCaseInTestSequence").each(function () {
        testcases = testcases + this.id + "/";
    });
    refreshTestsequence(testcases);
});

// Test Case Selection Modal initialization
$('#modal-testcase-selection').on('show.bs.modal', function () {
    $(".testCaseSelector").each(function () {
        if(this.checked) {
            this.checked = false;
        }
        if($("#testCasesList").has($.escapeSelector(this.id)).length > 0) {
            $(this).parent().parent().addClass("d-none");
        } else {
            $(this).parent().parent().removeClass("d-none");
        }
    });
    if( $("#testcase-selection").find("> div ").not('.d-none').length > 0) {
        $("#testCaseSelectorPlaceholder").addClass("invisible");
    } else {
        $("#testCaseSelectorPlaceholder").removeClass("invisible");
    }
});

// updates the SUTVersions and Duration of the testsequence
function refreshTestsequence(cases) {

    var url = currentURL().takeFirstSegments(4).appendSegment("info").toString();

    var posting = $.get(url, {
        newTestcases: cases
    });

    /* Alerts the results */
    posting.done(function (response) {
        var result = JSON.parse(response);
        var field = document.getElementById("testsequenceSUTVersionFrom");
        field.textContent = result.SUTVersionFrom;
        field = document.getElementById("testsequenceSUTVersionTo");
        field.textContent = result.SUTVersionTo;
        field = document.getElementById("testsequenceTime");
        var duration = "";

        if(result.DurationHours === 0 && result.DurationMin === 0){
            duration = "No Test Duration";
        } else {
            if(result.DurationHours > 0){
                if(result.DurationHours === 1){
                    duration = result.DurationHours + " Hour ";
                } else {
                    duration = result.DurationHours + " Hours ";
                }
            }
            if(result.DurationMin > 0){
                if(result.DurationMin === 1){
                    duration = duration + result.DurationMin+ " Minute ";
                } else {
                    duration = duration + result.DurationMin+ " Minutes ";
                }
            }
        }
        field.textContent = duration;
    }).fail(function (response) {
        $("#modalPlaceholder").empty().append(response.responseText);
        $('#errorModal').modal('show');
    });
}

function reloadDragAndDropFeature() {

    $('.sortable').sortable({
        placeholderClass: 'list-group-item',
        handle: '.test-sequence-reorder',
        containment: "#sortable-container",
        forcePlaceholderSize: true,
        forceHelperSize: true,
        cancel: ' ',
    });
}
