/*
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");
$.getScript("/static/js/util/ajax.js");

/* Button Assignment */
//List
$("#buttonNewTestSequence")      .click(newTestSequence);
$("#buttonNewTestSequenceDisabled").click(showSigninHint);
$("#buttonFirstTestSequence")    .click(newTestSequence);
$("#buttonNewLabel")             .click(function(event) { /* nothing yet */});
$(".testSequenceLine")           .click(showTestSequence);
//Show
$("#buttonBack")                 .click(backToTestSequenceList);
$("#buttonDeleteTestsequenceConfirmed")  .click(deleteTestSequence);
$("#buttonEdit")                 .click(editTestSequence);
$("#buttonHistory")              .click(showTestSequenceHistory);
//$("#buttonRevertConfirmed")  .click(function (event) { revertTestSequence(event); });
//History
$("#buttonBackToSequence")       .click(backToTestSequence);
$(".versionLine")                .click(showTestSequenceVersion);
//New
$("#buttonAbort")               .click(backToTestSequenceList);
$("#buttonSaveNew")             .click(saveTestSequence);
//Edit
$("#buttonSave")                .click(updateTestSequence);
$("#buttonAbortEdit")           .click(backToTestSequence);
//Execute
$("#buttonExecute")                      .click(execute);



/* AJAX-Functions */
/* loads the new test sequence form */
function newTestSequence(event) {
    ajaxRequestFragment(event, "new", "", "GET");
}

/*show sign in hint if not signed in and button is pressed*/
function showSigninHint(event) {
    event.preventDefault();
    $("#signin-link").tooltip('show');
}

/* loads the chosen test sequence */
function showTestSequence(event) {
    ajaxRequestFragment(event, event.target.id, "", "GET");
}

/* loads the chosen test sequence version*/
function showTestSequenceVersion(event) {
    var url = urlify(window.location.pathname).takeFirstSegments(5).toString();
    // Get version number. When clicking on an element that is in the .versionLine, check the parent of
    // this element until the parent is the versionLine with the id
    var ind = event.target.id;
    while (ind === "") {
        event.target = event.target.parentNode;
        ind = event.target.id;
    }
    ajaxRequestFragment(event, url + "?version=" + ind, "", "GET");
}

/* saves the test sequence */
function saveTestSequence(event) {
    var history = urlify(window.location.pathname).removeLastSegments(1).toString() + "/";
    ajaxRequestFragmentWithHistory(event, "save", getDataNewTestSequence(), "POST", history);
}

/* deletes a test sequence */
function deleteTestSequence(event) {
    var history = urlify(window.location.pathname).removeLastSegments(1).toString() + "/";
    $('#deleteTestSequenceModal').on('hidden.bs.modal', function () {
        ajaxRequestFragmentWithHistory(event, window.location.pathname, "", "DELETE", history);
    }).modal('hide');
}

/* edits a test sequence */
function editTestSequence(event) {
    var ver =$('#inputTestsequenceVersion').find("option:selected").val();
    ajaxRequestFragment(event, window.location.pathname + "/edit", { version: ver }, "GET");
}

/* revert test sequence to selected version */
function revertTestSequence(event) {
    // not yet implemented
}


/* saves the test sequence */
function updateTestSequence(event) {
    $('#modal-testsequence-save').on
    (
        'hidden.bs.modal',
        handleEdit(event, $('#minorUpdate').is(':checked'))
    ).modal('hide');
}

/* show test sequence history */
function showTestSequenceHistory(event) {
    ajaxRequestFragment(event, window.location.pathname + "/history", "", "GET");
}

/* steps back to the test sequence  */
function backToTestSequence(event) {
    var requestURL = urlify(window.location.pathname).takeFirstSegments(5).toString();
    ajaxRequestFragment(event, requestURL, "", "GET");
}

/* steps back to the test sequence list */
function backToTestSequenceList(event) {
    var requestURL = getProjectURL() + "/" + "testsequences" + "/";
    ajaxRequestFragment(event, requestURL, "", "GET");
}

// handleEdit either updates the current version or saves the edited version as newest version, depending
// on the handling parameter
function handleEdit(e, isMinor) {

    /* stop form from submitting normally */
    e.preventDefault();

    var url = urlify(window.location.pathname).removeLastSegments(1).toString();
    /* Send the data using post with element ids*/
    var posting = $.ajax({
        url: url + "/update?fragment=true",
        type: "PUT",
        data: getDataEdit(isMinor)
    });
    /* Alerts the results */
    posting.done(function (response) {
        var historyText = urlify(window.location.pathname).takeFirstSegments(4).toString();
        historyText = historyText + "/" + posting.getResponseHeader("newName");
        $('#tabTestsequences').empty().append(response);
        history.pushState('data', '', historyText);
    }).fail(function (response) {
        $("#modalPlaceholder").empty().append(response.responseText);
        $('#errorModal').modal('show');
    });
}

// getDataEdit return an array with information of the test sequence to edit
function getDataNewTestSequence() {
    var testcases = gatherTestSequenceIDs();
    return {
        inputTestSequenceName: $('#inputTestSequenceName').val(),
        inputTestSequenceDescription: $('#inputTestSequenceDescription').val(),
        inputTestSequencePreconditions: $('#inputTestSequencePreconditions').val(),
        inputTestSequenceTestCase: testcases,
        inputTestSequenceLabels: JSON.stringify(getTestSequenceLabelsInput()),
        inputSUTVersion: $('#inputSUTVersion').val(),
        inputTestSequenceVersion: $('#inputTestSequenceVersion').val(),
        inputTestSequenceTime: $('#inputTestSequenceTime').val()
    }
}

// getTestSequenceLabelsInput returns a list with the selected labels
function getTestSequenceLabelsInput() {
    // testSequenceLabels contains the the labels of the test case
    var testSequenceLabels = [];
    //  Get index of selected labels in dropdown
    var labelsValues = $('#labels').find('option:selected').map(function(a, item){return item.value;});

    // Add the selected labels to testSequenceLabels
    $.each(labelsValues, function(index, value) {
        testSequenceLabels.push(projectLabels[value])
    });

    return testSequenceLabels;
}

// getDataEdit return an array with information of the test sequence to edit
function getDataEdit(isMinor) {
    var testcases = gatherTestSequenceIDs();
    return {
        isMinor: isMinor,
        inputCommitMessage: $('#inputCommitMessage').val(),
        version: "{{ GetTestSequenceVersion.VersionNr }}",
        inputTestSequenceName: $('#inputTestSequenceName').val(),
        inputTestSequenceDescription: $('#inputTestSequenceDescription').val(),
        inputTestSequencePreconditions: $('#inputTestSequencePreconditions').val(),
        inputTestSequenceTestCase: testcases,
        inputTestSequenceLabels: JSON.stringify(getTestSequenceLabelsInput()),
        inputSUTVersion: $('#inputSUTVersion').val(),
        inputTestSequenceVersion: $('#inputTestSequenceVersion').val(),
        inputTestSequenceTime: $('#inputTestSequenceTime').val()
    }
}

function gatherTestSequenceIDs() {
    var testcases = "";
    $(".testCaseInTestSequence").each(function () {
        testcases = testcases + this.id + "~";
    });
    return testcases.slice(0, -1);
}

/* loads the start page of the test seq execution */
function execute(event) {
    ajaxRequestFragment(event, window.location.pathname + "/execute", "", "GET");
}