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

/**
 * Adds the listeners on page load (executed in new-project.tmpl)
 */
function initializeProjectCreateListener() {

// attach a handler to the import input
    $("#importProject").change(function () {
        validateImport(event);
    });

    $("#inputProjectLogo").change(function () {
        validateProjectImage(this);
    });
}

/**
 * Validate the import for file-type json
 */
function validateImport() {

    let file = document.getElementById('importProject').files[0];

    // Check if file has type json
    if (file.type !== "application/json") {
        document.getElementById('importProject').value = "";
        displayWrongFileModal();
    }
}

/**
 * Validate the input for file-type image
 */
function validateProjectImage(input) {

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

        reader.onload = e => $('#previewProjectLogo')
            .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 {
            document.getElementById('inputProjectLogo').value = "";
            displayWrongFileModal();
        }
    }
}

/**
 * Display Modal for worng file
 */
function displayWrongFileModal() {
    $('#errorModalTitle').html("File not supported");
    $('#errorModalBody').html("This file ist not supported. Please select a valid file.");
    $('#modal-generic-error').modal('show');
}

/* attach a handler to the create button */
$("#newProjectForm").submit(function (event) {

    let uploadedFile = document.getElementById('importProject').files[0];

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

    /* get the action attribute from the <form action=""> element */
    const url = $(this).attr('action');

    var jsonString = "";

    if (uploadedFile != null) {

        // reader for import
        let reader = new FileReader();
        reader.onload = function (e) {

            let contents = e.target.result;
            var json = JSON.parse(contents);
            jsonString = JSON.stringify(json);

            $.post(url, {

                inputProjectName: $('#inputProjectName').val(),
                inputProjectDesc: $('#inputProjectDesc').val(),
                inputProjectLogo: $('#previewProjectLogo').attr("src"),
                optionsProjectVisibility: document.querySelector('input[name="optionsProjectVisibility"]:checked').value,
                inputImport: jsonString

            }).done((request, textStatus, data) => {

                window.location.href = urlify("").appendCodedSegment(data.getResponseHeader("signedInUser")).appendCodedSegment(data.getResponseHeader('newName')).toString();

            }).fail(request => {

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

            });
        };
        reader.readAsText(uploadedFile);


    } else {

        /* Send the data using post with element ids*/
        $.post(url, {

            inputProjectName: $('#inputProjectName').val().trim().replace(/\s\s+/g, ' '),
            inputProjectDesc: $('#inputProjectDesc').val(),
            inputProjectLogo: $('#previewProjectLogo').attr("src"),
            optionsProjectVisibility: document.querySelector('input[name="optionsProjectVisibility"]:checked').value,

        }).done((request, textStatus, data) => {

            window.location.href = urlify("").appendCodedSegment(data.getResponseHeader("signedInUser")).appendCodedSegment(data.getResponseHeader('newName')).toString();

        }).fail(request => {

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

        });
    }
});

$(function() {
    //If the validator is used, the unique method is added or overwritten if already existent
    if ($.validator) {
        function uniqueTestCaseNameMethod(value, element, param) {
            return !projects.includes(value.trim().replace(/\s\s+/g, ' ')) || !param || this.optional(element);
        }

        if (!$.validator.methods.unique) {
            $.validator.addMethod("unique", uniqueTestCaseNameMethod, "A project with this name already exists.");
        } else {
            $.validator.methods.unique = uniqueTestCaseNameMethod;
        }

        const newProjectForm = $("#newProjectForm");
        if (newProjectForm.val() === "") {
            newProjectForm.validate({
                // requirements for formfields
                rules: {
                    inputProjectName: {
                        required: true,
                        unique: true,
                        minlength: 4
                    }
                },
                // error messages
                messages: {
                    inputProjectName: {
                        required: "Please enter a name for the new project.",
                        minlength: "The project name must consist of at least 4 characters.",
                        unique: "A project with this name already exists."
                    },
                },
                // error message placement
                errorElement: "div",
                errorPlacement: function(error, element) {
                    // Add the `help-block` class to the error element

                    error.addClass("form-control-feedback");

                    // Add `has-feedback` class to the parent div.form-group
                    // in order to add icons to inputs
                    element.parents(".col-sm-5").addClass("has-feedback");

                    if (element.prop("type") === "checkbox") {
                        error.insertAfter(element.parent("label"));
                    } else {
                        error.insertAfter(element);
                    }

                    // Add the span element, if doesn't exists, and apply the icon classes to it.
                    if (!element.next("span")[0]) {
                        $("<span class='glyphicon glyphicon-remove form-control-feedback'></span>").insertAfter(element);
                    }

                },
                success: function (label, element) {
                    // Add the span element, if doesn't exists, and apply the icon classes to it.
                    $(element).parents(".col-sm-10").addClass(" text-success").removeClass("text-danger");
                    $(element).addClass("form-control-success").removeClass("text-danger");
                    $('#buttonCreateProject').removeAttr("disabled");

                },
                highlight: function (element, errorClass, validClass) {
                    $(element).parents(".col-sm-10").addClass(" text-danger").removeClass("text-success");
                    $(element).addClass("form-control-danger").removeClass("text-danger");
                    $('#buttonCreateProject').attr("disabled", "");
                },
                unhighlight: function (element, errorClass, validClass) {
                    $(element).parents(".col-sm-10").addClass("text-success").removeClass("text-error");
                    $(element).addClass("form-control-success").removeClass("text-danger");
                }
            });
        }
    }
});

/**
 * 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 "Enter":
            buttonString = "buttonCreateProject";
            break;
    }
    if (document.getElementById(buttonString)) {
        document.getElementById(buttonString);
    }
}

$('.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"));
