$(function () {

    $('[data-toggle="tooltip"]').tooltip({
        placement: 'auto'
    }); // tooltip

    if (['numeric_with_custom_unit', 'compact_currency', 'standard_currency']
        .includes($("#display-format").val())
    ) {
        $("#custom-unit-input").attr("disabled", false)
    } else {
        $("#custom-unit-input").attr("disabled", true)
    }


    if ($("#compare-with").val() != "compare_with_a_fixed_target_value") {
        $("#target-value-input").attr("disabled", true)
    } else {
        $("#target-value-input").attr("disabled", false)
    }


    $(document).on('change', "#function", function () {
        let conditional_functions = [
            "conditional_count",
            "conditional_sum",
            "conditional_average",
            "conditional_max",
            "conditional_min"
        ];

        if (conditional_functions.includes($("#function").val())) {
            $(".filter-container input, .filter-container select").attr("disabled", false)
            $(".filter-container").attr("disabled", false).fadeIn();
            $(".conditional-only").fadeIn();

        } else {
            $(".filter-container input, .filter-container select").attr("disabled", true)
            $(".filter-container").attr("disabled", true).fadeOut();
            $('#display-format').val('percentage');
            $(".conditional-only").fadeOut();

        }
    });

    if ($("#drill-down").is(':checked')) {
        $("#drill-down-columns").attr("disabled", false)
    } else {
        $("#drill-down-columns").attr("disabled", true)

    }

    $('body').on("click", "#drill-down", function (e) {
        if ($(this).is(':checked')) {
            $("#drill-down-columns").attr("disabled", false)
        } else {
            $("#drill-down-columns").attr("disabled", true)

        }
    });

    $("#global-loader").hide();

    $('input.type-step').off();

    $('a[href="#type"]').off();
    $('a[href="#setup"]').off();

    $(document).on("click", ".btn-previous", function () {
        $(".error").hide();
    });

    $('a[href="#type"]').on('click', function (event) {

        $("input.btn-next").removeClass("type-step setup-step disabled")
            .addClass("type-step")
            .css("display", "block");
        $("input.btn-previous").css("display", "none");
        $("input.btn-finish").css("display", "none");

        $("#error").hide();
        $('#tabs a[href="#type"]').tab('show');

    });

    $('a[href="#setup"]').on('click', function (event) {

        stepTypeProcess(event);

    });

    $('a[href="#data"]').on('click', function (event) {

        $("input.btn-previous").removeClass("type-step-previous").addClass("setup-step-previous");

        $(".btn-previous").css("display", "block");
        $("input.btn-next").removeClass("type-step setup-step");
        $("input.btn-next").addClass("setup-step");
        $(document).on("click", ".type-step-previous", function () {
            $(`#tabs a[href="#type"]`).tab('show');
            $("input.btn-next").removeClass("setup-step").addClass("type-step");
            $("input.btn-previous").hide();

        });

        stepSetupProcess(event);

    });

    $('form input[name=metric_type]').change(function () {

        if ($(this).attr('value') == "info_box_with_icon") {
            $("#info-box-icon-drop-menu").fadeIn();

        } else {
            $("#info-box-icon-drop-menu").fadeOut();
        }

        if ($(this).attr('value') != "gauge_chart") {
            $("#metric-color-drop-menu").css("visibility", "visible");

        } else {
            $("#metric-color-drop-menu").css("visibility", "hidden");
        }


    });


    $(document).on('click', "input.type-step", function (event) {

        stepTypeProcess(event);
    });

    $(document).on("click", ".setup-step-previous", function () {
        $(`#tabs a[href="#setup"]`).tab('show');
        $(".btn-finish").css("display", "none");
        $(".btn-next").css("display", "block").removeClass("disabled");
        $(".btn-previous").css("display", "block").removeClass("disabled");
        $(".error").hide();
        $("input.btn-previous").removeClass("setup-step-previous").addClass("type-step-previous");
    });


    $(document).on('click', "input.setup-step", function (event) {

        stepSetupProcess(event);
    });


    $(document).on('click', "input.btn-finish", function (event) {

        stepFinishProcess(event);
    });



    $(document).on('change', "#performance-data-table", function (event) {
        if ($(`#${$(this).attr("id")} :selected`).val()) {
            let url = $(`#${$(this).attr("id")}`).data("url") + "/" + $("#connection").data("connection") + "/" + $(`#${$(this).attr("id")} :selected`).val() + "/get_columns";
            let currentElementId = $(this).attr("id")
            let types = ["date", "datetime", "char", "varchar", "string", "timestamp"];
            $.ajax({
                type: "GET",
                url: url,
                contentType: false,
                processData: false,
                dataType: "json",
                beforeSend: function () {
                    $("#global-loader").fadeIn();
                },
                success: function (response) {
                    let chartType = $('input[name="metric_type"]:checked').val();
                    let currentSelectBox = $(`#${currentElementId}`).parent().parent().next().find("select").attr("id");
                    updateSelectBox(currentSelectBox, response.data, true, "Please Select Column");
                    updateSelectBox("drill-down-columns", response.data, false);
                    updateSelectBox("filtration-column", response.data, true, "Please Select Filtration Column");
                }
            });

            $.ajax({
                type: "GET",
                url: url + "?types=" + encodeURIComponent(JSON.stringify(types)),
                contentType: false,
                processData: false,
                dataType: "json",
                success: function (response) {
                    $("#global-loader").fadeOut();
                    updateSelectBox("date-filter-column", response.data, true, "Please Select Column", function () {
                        if (response.data.length === 0) {
                            $('#date-range').attr('disabled', true);
                            $('#date-range-hidden').attr('disabled', false);
                            $('#compare-with option[value="compare_with_preceding_period"]').hide();
                            $('#compare-with option[value="compare_with_same_time_last_year"]').hide();

                        } else {
                            $('#date-range').attr('disabled', false);
                            $('#date-range-hidden').attr('disabled', true);
                            $('#compare-with option[value="compare_with_preceding_period"]').show();
                            $('#compare-with option[value="compare_with_same_time_last_year"]').show();

                        }
                    });
                }

            });


        }
    });



    $(document).on('change', "#display-format", function () {
        if (['numeric_with_custom_unit', 'compact_currency', 'standard_currency']
            .includes($("#display-format").val())) {
            $("#custom-unit-input").attr('disabled', false)
        } else {
            $("#custom-unit-input").attr('disabled', true)

        }
    });

    $(document).on('change', "#compare-with", function () {
        if ($('#compare-with').val() != "compare_with_a_fixed_target_value") {
            $("#target-value-input").attr('disabled', true)
        } else {
            $("#target-value-input").attr('disabled', false)

        }
    });


    $('#security-type').change(function () {
        if ($('#security-type :selected').val() == "public") {
            $("#confirm-public-metric-modal").modal({
                keyboard: false,
                backdrop: 'static',
                show: true
            });
        } else if ($('#security-type :selected').val() == "private") {
            $("#groups").attr("disabled", false);

        }
    });

    $("#saveBtn-confirm-public-metric").on('click', function () {
        $("#groups").attr("disabled", true);

        $("#confirm-public-metric-modal").modal("hide");
    });

    $("#cancelBtn-confirm-public-metric").on('click', function () {

        $("#groups").attr("disabled", false);

        $('#security-type').val("private").change();
    });




});


function sendAjaxRequest(formId, fields, tab, errorTab = null, loader = true, callback) {
    var form = document.getElementById(formId);
    let url = $(`#${formId}`).attr('data-url');
    $.ajax({
        type: "POST",
        url: url,
        data: new FormData(form),
        contentType: false,
        processData: false,
        dataType: "json",
        beforeSend: function () {
            if (loader)
                $("#global-loader").fadeIn();
        },
        success: function (response) {

            if (response.demo) {
                window.parent.$(`#demo-modal`).find('h5').text(response.demo).show();
                window.parent.$(`.modal`).modal('hide');

                window.parent.$(`#demo-modal`).modal('show');
            }


            if (loader)
                $("#global-loader").fadeOut();
            if (tab)
                $(`#tabs a[href="#${tab}"]`).tab('show');
            $('input.type-step').off();
            $("#error").hide();
            if (callback)
                callback();

        }, error: function (response) {
            if (loader)
                $("#global-loader").fadeOut();

            if (tab)
                $(`#tabs a[href="#${errorTab}"]`).tab('show');

            response = response.responseJSON;
            if (response.errors) {
                fields.every(error => {
                    if (response.errors[error]) {

                        $(`#error`).text(response.errors[error][0]).show();
                        $(`#error`).attr("title", response.errors[error][0]).show();

                        return false;
                    }
                    return true;

                });
                $("#error").show();
            }

        }
    });

}

function resetSelectBox(id, placeholder, placeholderSentence = null) {
    $(`select[id="${id}"]`).empty();

    if (placeholder)
        $(`select[id="${id}"]`).append(
            `<option value="">${placeholderSentence}</option>`
        );

}

function updateSelectBox(id, data, placeholder, placeholderSentence = null, callback = null) {
    $(`select[id="${id}"]`).empty();

    if (placeholder)
        $(`select[id="${id}"]`).append(
            `<option value="">${placeholderSentence}</option>`
        );

    $.each(data, function (key, value) {
        $(`select[id="${id}"]`).append(
            '<option value="' + value + '">' + value[0].toUpperCase() + value.substring(1) + "</option>"
        );
    });

    if (callback)
        callback();
}


function stepTypeProcess(event) {
    event.stopPropagation();

    sendAjaxRequest("metric-type-form", ["metric_type", "metric_color", "info_box_icon"], 'setup', null, true, function () {
        $("input.btn-next").removeClass("type-step").addClass("setup-step").removeClass("disabled").show();
        $("input.btn-finish").hide();

        $("input.btn-previous").removeClass("disabled").addClass("type-step-previous").show();
        $(document).on("click", ".type-step-previous", function () {
            $(`#tabs a[href="#type"]`).tab('show');
            $("input.btn-next").removeClass("setup-step").addClass("type-step");
            $("input.btn-previous").hide();

        });
    });

}


function stepSetupProcess(event) {
    event.stopPropagation();

    sendAjaxRequest("metric-type-form", ["metric_type", "metric_color", "info_box_icon"], null, null, false, function () {

        sendAjaxRequest("metric-setup-form", ["name", "title", "category", "connection", "security_type", "groups"], 'data', 'setup', false, function () {

            $("input.btn-previous").removeClass("type-step-previous").addClass("setup-step-previous");


        });


        $(document).on("click", ".setup-step-previous", function () {
            $(`#tabs a[href="#setup"]`).tab('show');
            $(".btn-finish").css("display", "none");
            $(".btn-next").css("display", "block").removeClass("disabled");
            $(".btn-previous").css("display", "block").removeClass("disabled");
            $(".error").hide();
            $("input.btn-previous").removeClass("setup-step-previous").addClass("type-step-previous");
        });

    });

}

function stepFinishProcess(event) {
    event.stopPropagation();

    let fields = ["performance_data_table", "calculation_column", "filtration_column", "filtration_value", "function", "date_range", "metric_direction", "date_filter_column", "date_range", "display_format", "custom_unit_input", "compare_with", "target_value_input", "drill_down", "drill_down_columns"];
    $("#global-loader .loader-text").text("Please wait while creating the Metric / KPI ...");

    sendAjaxRequest("metric-data-form", fields, null, null, true, function () {

        if (window.parent) {
            window.parent.$('#edit-metric-modal').modal('hide');
            window.parent.reloadPagePartially("metric-search-form", ".metric-parent-container", ".metric-parent-container", true);
        }
        $("#global-loader .loader-text").text("");

    });

}
