/*
 * This file is part of SystemTestPortal.
 * Copyright (C) 2017-2018  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/>.
 */

const emailReg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

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

/**
 * Saves the account settings using a put request
 */
$("#saveButton").off("click").on("click", function () {
    const email = $("#inputNewEmail").val();
    const bio = $("#inputUserBio").val();
    const isShownPublic = $("#inputIsShownPublic").prop('checked');
    const isEmailPublic = $("#inputIsEmailPublic").prop('checked');
    const projectHeaderMode = document.querySelector('input[name="optionProjectHeaderMode"]:checked').value;
    const profilePicture = $('#inputProfileImage').attr("src");

    if (!emailReg.test(email)) {
        showErrorModal("Please enter a valid email address.");
        return;
    }


    $.ajax({
        url: currentURL(),
        type: "PUT",
        data: {
            "user": target,
            "email": email,
            "bio": bio,
            "isShownPublic": isShownPublic,
            "isEmailPublic": isEmailPublic,
            "projectHeaderMode" : projectHeaderMode,
            "profilePicture": profilePicture,
        },
        statusCode: {
            200: function () {
                goToProfile();
            }
        }
    }).fail(response => {
        showErrorModal(response.responseText)
    });
});

/**
 * Show a modal to change the password
 */
$("#changePasswordButton").off("click").on("click", function () {
    $("#changePasswordModal").modal("show");
});

/**
 * Sends a put request to change the users password
 */
$("#savePasswordButton").off("click").on("click", function () {
    const userPassword = $("#inputOldPassword").val();
    const newPassword = $("#inputNewPassword").val();
    const newPasswordRepeat = $("#inputNewPasswordRepeat").val();

    if (newPassword != newPasswordRepeat && newPassword != "") {
        showError("The new password fields must match.");
        return;
    } else {
        if (newPassword.length < 8) {
            showError("The new password must be at least 8 characters long.");
            return;
        }
    }


    if (userPassword == "") {
        showError("You need to enter your current password to change your password.");
        return;
    }

    $.ajax({
        url: currentURL() + "/changePassword",
        type: "PUT",
        data: {
            "user": target,
            "userPassword": userPassword,
            "newPassword": newPassword,
        },
        statusCode: {
            200: function () {
                $("#changePasswordModal").modal("hide");
            }
        }

    }).fail(response => {
        $("#changePasswordModal").modal("hide");
        showErrorModal(response.responseText)
    });
});


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

    function displayWrongFileModal() {
        showErrorModal("This file ist not supported. Please select a valid file.");
        $(input).val("");
    }

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

        reader.onload = e => $('#inputProfileImage').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();
    }
}


/**
 * Change the current location to the profile page
 */
function goToProfile() {
    window.location = currentURL().takeFirstSegments(currentURL().segments.length - 1);
}

/**
 * Shows a modal containing an error message
 * @param error The message to be displayed
 */
function showErrorModal(error) {
    $("#errorModalResponseTextEditProfile").empty().append(error);
    $("#errorModal").modal("show");
}

/**
 * Show error in the change password modal
 * @param error The message to be displayed
 */
function showError(error) {
    $("#newPasswordFeedback").text(error);
}