/*
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 (exectuted in settings.tmpl)
function initializeSettingsClickListener() {
    //Submit button of settings
    $('#SaveChangesProjectSettingsButton').click(function (event) {
        saveSettings(event)
    });
    // Project delete button
    $('#buttonDeleteProject').click(function (event) {
        deleteProject(event)
    });

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

// this function deletes the current project.
function deleteProject(event) {
    $("#deleteProject").modal('hide');
    //prevents the default event behaviour
    event.preventDefault();

    //sends delete request to the serverr
    var path = currentURL().toString();
    var posting = $.ajax({
        url: path,
        type: "DELETE",
        data: ""
    });

    //redirects to the start page or shows error modal
    posting.done(function (response) {
        location.href = "http://" + location.host + "/";
        return true;
    }).fail(function (response) {
        $("#modalPlaceholder").empty().append(response.responseText);
        $('#errorModal').modal('show');
    });
}

// sends the selected settings to the server
function saveSettings(event) {
    var path = currentURL().toString() + "/";

    event.preventDefault();
    var posting = $.ajax({
        url: path,
        type: "POST",
        data: getSettingsParams()
    });
    posting.done(function (response) {
        location.replace(location.pathname);
        return true;
    }).fail(function (response) {
        $("#modalPlaceholder").empty().append(response.responseText);
        $('#errorModal').modal('show');
    });
}

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

// processes image upload
function readImageInput(input) {

    function displayWrongFileModal() {
        $('#modal-wrong-file').modal('show');
        $(input).val("");
    }

    function applyImage(image) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('#inputProjectImage').attr('src', e.target.result);
        };
        reader.readAsDataURL(image);
    }

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