/*
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/ajax.js");

// 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
    $('#buttonDeleteConfirmed').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) {
    //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() + "/";
    ajaxRequestFragment(event, path, getSettingsParams(), "POST");
}

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

// processes image upload
function readImageInput(input) {

    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function(e) {
            $('#projectImageSettings').attr('src', e.target.result);
        };

        reader.readAsDataURL(input.files[0]);
    }
}