$(document).ready(function() {
    addUser();
    listing();
    downloadWorksheet();
    if ($("#form-risk").length) {
        onCalculate();
        onCreateWorksheet();
        loadDinAssetData();
        $("#asset").on("change", function(e) {
            loadDinAssetData();
            $("#result-box").removeClass("result-existing");
        });
        $("#form-risk").on("submit", function(e) {
            e.preventDefault();
            $("#calculate").trigger("click");
        });
    }
});

// Message Box for alerts
function messageBox(status, message) {
    let msg = $("#message");
    if (status) {
        msg.removeClass("failure").addClass("success");
    } else {
        msg.removeClass("success").addClass("failure");
    }
    msg.empty().append("<p>" + message + "</p>");
    msg.slideDown(300, function() {
        window.setTimeout(function() {
            msg.slideUp(300);
        }, 1400);
    })
}

// Add new user
function addUser() {
    // Add new user
    $(".add-user [data-js='listing--details']").on("click", function(e) {
        let form = $(this).parents(".form"),
            form_data = form.serializeObject();
        if (form[0].checkValidity()) {
            e.preventDefault();
            form_data["active"] = $("#inputActive").is(":checked") ? 1 : 0;
            $.ajax({
                url: "/admin/user",
                method: "post",
                data: form_data,
                success: function (data) {
                    messageBox(true, "User erfolgreich angelegt. Sie werden nun zur Übersicht weitergeleitet.");
                    window.setTimeout(function() {
                        window.location.href = "/admin/dashboard";
                    }, 2000);
                },
                error: function (xhr, status, statusmsg) {
                    console.log(xhr);
                    messageBox(false, xhr.responseJSON);
                },
                dataType: "json"
            });
        }
    });
}

// List users and edit them
function listing() {
    // Open user details
    $("[data-js='listing--opener']").on("click", function() {
        let that = $(this).parents("li");
        if (that.hasClass("open")) {
            that.find(".listing--details").slideUp(500);
            that.removeClass("open");
        } else {
            $("[data-js='listing--opener']").parents("li").removeClass("open");
            $(".listing--details").slideUp(500);
            that.find(".listing--details").slideDown(500);
            that.addClass("open");
        }
    });

    // Send AJAX request for user edit
    $(".listing [data-js='listing--details']").on("click", function(e) {
        let form = $(this).parents(".form"),
            form_data = form.serializeObject(),
            userId = form_data["id"];
        if (form[0].checkValidity()) {
            e.preventDefault();
            form_data["active"] = $("#inputActive" + userId).is(":checked") ? 1 : 0;
            $.ajax({
                url: "/admin/user",
                method: "patch",
                data: form_data,
                success: function (data) {
                    messageBox(true, "User erfolgreich aktualisiert.");
                },
                error: function (xhr, status, statusmsg) {
                    console.log(xhr);
                    messageBox(false, xhr.responseJSON);
                },
                dataType: "json"
            });
        }
    });

    // Send new password to user
    $("[data-js='listing--password']").on("click", function(e) {
        let userId = $(this).parents("li").data("userid"),
            userName = $(this).parents("li").data("username"),
            confirmAction = confirm("Möchten Sie dem User " + userName + " ein neues Passwort zuweisen?");
        if (confirmAction === true) {
            $.ajax({
                url: "/admin/new-password",
                method: "post",
                data: {
                    id: userId
                },
                success: function (data) {
                    messageBox(true, "Passwort erfolgreich geändert. E-Mail ist an User " + userName + " versendet worden.");
                },
                error: function (xhr, msg, three) {
                    messageBox(false, "Fehler beim Erstellen eines neuen Passworts.");
                },
                dataType: "json"
            });
        }
    });
}

function loadDinAssetData() {
    $.ajax({
        url: "/get-benchmark-data",
        method: "get",
        data: { assetId: $("#asset").val() },
        success: function (data) {

            $('#benchmark')
                .find('option')
                .remove()
                .end()
            ;

            for (let i in data.benchmarkValues) {
                noBenchmarkData = true;
                $('#benchmark').append('<option value="' + i + '">' + data.benchmarkValues[i] + '</option>');
            }

            if (Object.keys(data.benchmarkValues).length <= 0) {
                $('#no-benchmark-data').show();
                $('#benchmark').prop( "disabled", true );
            } else {
                $('#no-benchmark-data').hide();
                $('#benchmark').prop( "disabled", false );
            }
        },
        error: function (xhr, msg, three) {
            messageBox(false, "Fehler bei der Anfrage.");
        },
        dataType: "json"
    });
}

function onCalculate() {
    $("#calculate").on("click", function (e) {
        e.preventDefault();
        if (checkInputs()) {
            $.ajax({
                url: "/calculate-risk",
                method: "post",
                data: $('#form-risk').serializeArray(),
                success: function (data) {
                    $('#resInspection').text(data['recCycleInspection']);
                    $('#resMaintenance').text(data['recCycleMaintenance']);

                    let percentage = "-";
                    if (data['costDiffCurRecPercentage'] !== null) {
                        percentage = (parseFloat(data['costDiffCurRecPercentage']) * 100) + " %";
                    }
                    $('#resPercentage').text(percentage);

                    let costDiff = "-";
                    if (data['costDiffCurCycleRecCycle'] !== null) {
                        costDiff = parseFloat(data['costDiffCurCycleRecCycle']).toFixed(2);
                        costDiff = costDiff.replace(/\./g, ",") + " €";
                    }
                    $('#resEuro').text(costDiff);

                    $("#result-box").addClass("result-existing");
                    $('html, body').animate({
                        scrollTop: $('#result-box').offset().top - 200
                    }, 500);
                },
                error: function (xhr, msg, three) {
                    messageBox(false, "Fehler bei der Anfrage.");
                },
                dataType: "json"
            });
        }
    });
}

function onCreateWorksheet() {
    $("#worksheet").on("click", function (e) {
        e.preventDefault();
        let result = window.confirm("Sie nutzen hiermit einen Ihrer Durchgänge.");
        if (result) {
            if (checkInputs()) {
                $.ajax({
                    url: "/create-worksheet",
                    method: "post",
                    data: $('#form-risk').serializeArray(),
                    success: function (data) {
                        console.log(data);
                        window.location = "/worksheet/" + data;
                    },
                    error: function (xhr, msg, three) {
                        messageBox(false, "Fehler bei der Anfrage.");
                    },
                    dataType: "json"
                });
            }
        }
    });

    $("#create-worksheet").on("click", function (e) {
        e.preventDefault();
        let result = window.confirm("Sie nutzen hiermit einen Ihrer Durchgänge.");
        if (result) {
            $.ajax({
                url: "/create-worksheet",
                method: "post",
                data: {
                    asset: $('#asset').val()
                },
                success: function (data) {
                    console.log(data);
                    window.location = "/worksheet/" + data;
                },
                error: function (xhr, msg, three) {
                    messageBox(false, "Fehler bei der Anfrage.");
                },
                dataType: "json"
            });
        }
    });
}

function checkInputs() {
    let cycleVal = $("#cycle").val();
    if (cycleVal === '') {
        messageBox(false, "Bitte geben Sie Ihren aktuellen Zyklus ein.");
        return false;
    } else {
        let cycleMin = parseInt($("#cycle").attr("min"));
        if (cycleVal < cycleMin) {
            $("#cycle").val(cycleMin);
            messageBox(false, "Zyklus an Minimal-Wert '" + cycleMin + "' angepasst.");
        }
        let cycleMax = parseInt($("#cycle").attr("max"));
        if (cycleVal > cycleMax) {
            $("#cycle").val(cycleMax);
            messageBox(false, "Zyklus an Maximal-Wert '" + cycleMax + "' angepasst.");
        }
    }
    return true;
}

function downloadWorksheet() {
    $("#download").on("click", function (e) {
        e.preventDefault();
        $.ajax({
            url: "/create-worksheet",
            method: "post",
            data: $('#form-risk').serializeArray(),
            success: function (data) {
                console.log(data);
                window.location = "/download/" + data;
            },
            error: function (xhr, msg, three) {
                messageBox(false, "Fehler bei der Anfrage.");
            },
            dataType: "json"
        });
    });
}
