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

/** Adds the listeners on page load (executed in settings.tmpl) */
function initializeIntegrationsSettingsListener() {
    $('#SaveIntegrationsSettingsButton').on("click", () => saveIntegrationSettings());
}

/** Function which gets called when the "Save" button got clicked */
function saveIntegrationSettings() {

    $.ajax({
        url: currentURL().toString(),
        type: "PUT",
        data: getIntegrationSettingsParams()

    }).done(() => {

        location.replace(location.pathname);
        return true;

    }).fail(response => {

        $("#modalPlaceholder").empty().append(response.responseText);
        $('#errorModalTitle').html("Invalid input");
        $('#errorModalBody').html("Your input was invalid. Please enter valid values.");
        $('#modal-generic-error').modal('show');

    });
}

/** Fetches the integration setting values */
function getIntegrationSettingsParams() {
    return {
        inputIsActive: document.getElementById('inputIsActive').checked,
        inputProjectID: $('#inputIntegrationGitlabProjectID').val(),
        inputProjectToken: $('#inputIntegrationGitlabProjectToken').val(),
    }
}

/**
 * Keyboard support
 */
$(document)
    .off("keydown.event")
    .on("keydown.event", function (event) {
        keyboardSupport(event)
    });


/**
 * keybindings
 * @param event
 */
function keyboardSupport(event) {
    //checks if focus is in textfields, areas, etc.

    switch (event.target.tagName) {
        case "INPUT":
        case "SELECT":
        case "TEXTAREA":
            return;
    }

    //Adds Keybindings
    let buttonString;
    switch (event.key) {
        case "Enter":
            buttonString = "buttonSave";
            break;
    }
    if (document.getElementById(buttonString) != null) {
        document.getElementById(buttonString).click();
    }
}

/**
 * Adds key listeners when modals closes
 */
$('.modal').on('hide.bs.modal', function (event) {
    $(document).on("keydown.event", function (event) {
        keyboardSupport(event);
    });
});

/**
 * Removes key listeners when modals open
 */
$('.modal').on('show.bs.modal', function (e) {
    $(document).off("keydown.event");

});