/*
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 initializeProjectSettingsListener() {

    $('#SaveProjectsSettingsButton').on("click", () => saveProjectSettings());

    $('#buttonDeleteProject').on("click", event => deleteProject(event));

    $('#ExportJsonProjectButton').on("click", event => exportProject(event));

    //Handle File Change
    $('input[type=file]').on("change", function () {
        readImageInput(this);
    });
}

/**
 * Deletes the current project.
 * @param event
 */
function deleteProject(event) {
    event.preventDefault();

    $("#deleteProject").modal('hide');

    $.ajax({

        url: currentURL().toString(),
        type: "DELETE",
        data: ""

    }).done(() => {

        location.href = "http://" + location.host + "/";
        return true;

    }).fail(response => {

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

    });
}

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

    $.ajax({
        url: currentURL().toString(),
        type: "POST",
        data: getProjectSettingsParams()

    }).done(() => {

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

    }).fail(response => {

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

    });
}

/** Fetches the project setting values */
function getProjectSettingsParams() {
    return {
        inputProjectName: $('#inputProjectName').val(),
        inputProjectDesc: $('#inputProjectDescription').val(),
        inputProjectLogo: $('#inputProjectImage').attr("src"),
        optionsProjectVisibility: document.querySelector('input[name="optionsProjectVisibility"]:checked').value
    }
}

/**
 * Processes image upload
 * @param input
 */
function readImageInput(input) {

    function displayWrongFileModal() {
        $('#errorModalTitle').html("File not supported");
        $('#errorModalBody').html("This file ist not supported. Please select a valid file.");
        $('#modal-generic-error').modal('show');
        $(input).val("");
    }

    function applyImage(image) {
        const reader = new FileReader();

        reader.onload = e => $('#inputProjectImage').attr('src', e.target.result);
        reader.readAsDataURL(image);
    }

    if (input.files && input.files[0]) {
        let file = input.files[0];
        if (file.type.startsWith("image"))
            applyImage(file);
        else
            displayWrongFileModal();
    }
}

/**
 * Export the project as json
 * @param event
 */
function exportProject(event) {

    let requestURL = currentURL();
    requestURL.appendSegment("export");

    let req = new XMLHttpRequest();
    req.onreadystatechange = handler;
    req.open("POST", requestURL, true);
    req.responseType = "blob";
    req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    req.send('project=' + requestURL.segments[4]);

    function handler() {
        if (this.readyState === this.DONE) {
            let blob = req.response;
            let link = document.createElement('a');
            let currentURL = window.location.href.split("/");
            let filename = currentURL[4] + "-STP_Project";
            link.download = filename + ".json";
            document.body.appendChild(link);
            link.href = window.URL.createObjectURL(blob);
            link.click();
            setTimeout(() => {
                document.body.removeChild(link);
                window.URL.revokeObjectURL(link);
            }, 100);
        }
    }
}

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


/**
 * 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 "E":
        case "e":
            buttonString = "buttonExportJSONProject";
            break;
        case "Enter":
            buttonString = "buttonSave";
            break;
    }
    if (document.getElementById(buttonString) != null) {
        document.getElementById(buttonString).click();
    }
}

$('.modal')
    .off("hide.bs.modal.keyboardsupport")
    .off("show.bs.modal.keyboardsupport")

    /* Adds key listeners when modals closes */
    .on('hide.bs.modal.keyboardsupport', () => $(document).on("keydown.event", keyboardSupport))

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