$(function () {

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

    $('body').on("click", ".data-filter-columns", function (e) {
        $(this).parent().is(".open") && e.stopPropagation();
    });

    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)

        }
    });


    $('.selectall').click(function () {
        if ($(this).is(':checked')) {
            $('.option').prop('checked', true);
            var total = $('input[name="data_filter_columns[]"]:checked').length;
            $(".dropdown-text").html('(' + total + ') Selected');
            $(".select-text").html(' Deselect');
        } else {
            $('.option').prop('checked', false);
            $(".dropdown-text").html('(0) Selected');
            $(".select-text").html(' Select');
        }
    });

    $("input[type='checkbox'].justone").change(function () {
        var a = $("input[type='checkbox'].justone");
        if (a.length == a.filter(":checked").length) {
            $('.selectall').prop('checked', true);
            $(".select-text").html(' Deselect');
        }
        else {
            $('.selectall').prop('checked', false);
            $(".select-text").html(' Select');
        }
        var total = $('input[name="data_filter_columns[]"]:checked').length;
        $(".dropdown-text").html('(' + total + ') Selected');
    });



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

    $('#data-filtration').multiselect();
    $('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=chart_type]').change(function () {

        let chartType = $('input[name="chart_type"]:checked').val();

        $('.type-step').attr('disabled', false);
        let colorPaletteTypes = ['pie-chart', '3d-pie-chart', 'donut-chart', '3d-donut-chart'];

        if (colorPaletteTypes.includes($(this).attr('value'))) {
            $("#sections-color-palette-drop-menu").fadeIn();

        } else {
            $("#sections-color-palette-drop-menu").fadeOut();
        }

        if (chartType == "pie-chart" || chartType == "3d-bar-chart" || chartType == "donut-chart" || chartType == "3d-donut-chart") {
            $('.x-axis-label').text("Segment axis");
            $('.y-axis-label').text("Values axis");
        } else if (chartType == "geo-chart") {
            $('.x-axis-label').text("Geographic Axis");
            $('.y-axis-label').text("Values axis");
        } else {
            $('.x-axis-label').text("X axis Settings");
            $('.y-axis-label').text("Y axis settings");

        }

        if (chartType == "timeseries") {
            $(".time-series").fadeIn();
            $(".data-filtration").fadeOut();
        } else {
        }

    });


    $(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) {
        // event.stopPropagation();
        // if ($('div.active').attr('id') == 'setup') {

        //     sendAjaxRequest("chart-type-form", ["chart_type", "widget_size", "map_selection"], null, false, function () {

        //         sendAjaxRequest("chart-setup-form", ["name", "title", "category", "connection", "security_type", "groups"], 'data', 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");
        //         });

        //     });
        // }

        stepSetupProcess(event);
    });


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


    $(document).on('change', "#x-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 chartType = $('input[name="chart_type"]:checked').val();
            let types = ["date", "datetime", "char", "varchar", "string", "timestamp"];

            if (chartType == "timeseries") {
                url = url + "?types=" + encodeURIComponent(JSON.stringify(types))
            }

            $.ajax({
                type: "GET",
                url: url,
                contentType: false,
                processData: false,
                dataType: "json",
                beforeSend: function () {


                    $("#global-loader").fadeIn();
                },
                success: function (response) {
                    let chartType = $('input[name="chart_type"]:checked').val();


                    $("#global-loader").fadeOut();
                    let currentSelectBox = $(`#${currentElementId}`).parent().parent().next().find("select").attr("id");
                    updateSelectBox(currentSelectBox, response.data, true, "Please Select Column");
                    if (chartType != "timeseries") {
                        $(".time-series").fadeOut();
                    }
                    $(".data-filtration").fadeOut();

                }

            });

        }
    });


    $(document).on('change', "#y-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")
            $.ajax({
                type: "GET",
                url: url,
                contentType: false,
                processData: false,
                dataType: "json",
                beforeSend: function () {

                    $("#global-loader").fadeIn();
                },
                success: function (response) {


                    $("#global-loader").fadeOut();
                    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);

                }

            });
        }

    });


    $(document).on('change', "#x-axis-column", function (event) {
        let TableSelectBox = $(`#${$(this).attr("id")}`).parent().parent().prev().find("select");
        if ($(`#${$(this).attr("id")} :selected`).val()) {


            let url = $(`#${$(this).attr("id")}`).data("url") + "/" + $("#connection").data("connection") + "/" + TableSelectBox.val() + "/" + $(`#${$(this).attr("id")} :selected`).val() + "/get_column_type";
            $.ajax({
                type: "GET",
                url: url,
                contentType: false,
                processData: false,
                dataType: "json",
                beforeSend: function () {

                    $("#global-loader").fadeIn();
                },
                success: function (response) {

                    let chartType = $('input[name="chart_type"]:checked').val();
                    let timestampDataTypes = ["timestamp", "date", "datetime"];
                    let numericDataTypes = ["bigint", "decimal", "double", "float", "int", "mediumint", "smallint", "tinyint"
                        , "unsignedbiginteger", "unsignedinteger", "unsignedmediuminteger", "unsignedsmallinteger", "unsignedtinyinteger"];

                    if (timestampDataTypes.includes(response.data) || chartType == "timeseries") {

                        if ($("#widgetSize").val() === "full") {
                            $("#date_range option[value='last_12_months']").prop("selected", true);
                            updateSelectBox("date_time_scale", ["quarters", "months"]);
                        } else if ($("#widgetSize").val() === "half") {
                            $("#date_range option[value='last_3_months']").prop("selected", true);
                            updateSelectBox("date_time_scale", ["months"]);
                        }


                        $(".time-series").fadeIn();
                        $(".data-filtration").fadeOut();
                        $("#global-loader").fadeOut();


                    }
                    else if (numericDataTypes.includes(response.data)) {
                        $(".time-series").fadeOut();
                        $(".data-filtration").fadeOut();
                        $("#global-loader").fadeOut();

                    } else {

                        let url = $(`.data-filter-columns`).data("url") + "/" + $("#connection").data("connection") + "/" + $(`#x-table :selected`).val() + "/" + $(`#x-axis-column :selected`).val() + "/get_values";
                        $.ajax({
                            type: "GET",
                            url: url,
                            contentType: false,
                            processData: false,
                            dataType: "json",
                            success: function (response) {

                                $(`.data-filter-columns`).empty();
                                $(`.data-filter-columns`).append(
                                    '<li><a href="#"><label><input type="checkbox" class="selectall" /><span class="select-text"> Select</span> All</label></a></li><li class="divider"></li>'
                                );

                                $.each(response.data, function (key, value) {
                                    $(`.data-filter-columns`).append(
                                        '<li><a class="option-link" href="#"><label><input name="data_filter_columns[]" type="checkbox" class="option justone" value="' + value + '"> ' + value + ' </label></a></li>'
                                    );
                                });

                                $('body').on("click", ".data-filter-columns", function (e) {
                                    $(this).parent().is(".open") && e.stopPropagation();
                                });
                                $('.option').prop('checked', true);

                                $('.selectall').prop('checked', true);
                                var total = $('input[name="data_filter_columns[]"]:checked').length;
                                $(".dropdown-text").html('(' + total + ') Selected');
                                $(".select-text").html(' Deselect');

                                $('.selectall').click(function () {
                                    if ($(this).is(':checked')) {
                                        $('.option').prop('checked', true);
                                        var total = $('input[name="data_filter_columns[]"]:checked').length;
                                        $(".dropdown-text").html('(' + total + ') Selected');
                                        $(".select-text").html(' Deselect');
                                    } else {
                                        $('.option').prop('checked', false);
                                        $(".dropdown-text").html('(0) Selected');
                                        $(".select-text").html(' Select');
                                    }
                                });

                                $("input[type='checkbox'].justone").change(function () {
                                    var a = $("input[type='checkbox'].justone");
                                    if (a.length == a.filter(":checked").length) {
                                        $('.selectall').prop('checked', true);
                                        $(".select-text").html(' Deselect');
                                    }
                                    else {
                                        $('.selectall').prop('checked', false);
                                        $(".select-text").html(' Select');
                                    }
                                    var total = $('input[name="data_filter_columns[]"]:checked').length;
                                    $(".dropdown-text").html('(' + total + ') Selected');
                                });
                                $("#global-loader").fadeOut();

                            }

                        });


                        $(".data-filtration").fadeIn();
                        $(".time-series").fadeOut();
                    }


                }, error: function () {


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

                }

            });
        } else {
            $(".time-series").fadeOut();
            $(".data-filtration").fadeOut();
        }

    });

    $(document).on('change', "#y-axis-column", function (event) {
        let TableSelectBox = $(`#${$(this).attr("id")}`).parent().parent().prev().find("select");
        if ($(`#${$(this).attr("id")} :selected`).val()) {


            let url = $(`#${$(this).attr("id")}`).data("url") + "/" + $("#connection").data("connection") + "/" + TableSelectBox.val() + "/" + $(`#${$(this).attr("id")} :selected`).val() + "/get_column_type";
            $.ajax({
                type: "GET",
                url: url,
                contentType: false,
                processData: false,
                dataType: "json",
                beforeSend: function () {


                    $("#global-loader").fadeIn();
                },
                success: function (response) {


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


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

                }

            });
        }

    });


    $(document).on('change', "#date_range", function (event) {
        let url = $(`#${$(this).attr("id")}`).data("url") + "/" + $(this).val() + "/get_scales";
        $.ajax({
            type: "GET",
            url: url,
            contentType: false,
            processData: false,
            dataType: "json",
            beforeSend: function () {


                $("#global-loader").fadeIn();
            },
            success: function (response) {


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

                updateSelectBox("date_time_scale", response.data);
            }

        });


    });


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

        }
    });

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

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

    $("#cancelBtn-confirm-public-chart").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) {
    $(`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>"
        );
    });

}


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

    sendAjaxRequest("chart-type-form", ["chart_type", "widget_size", "map_selection", "sections_color_palette"], '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("chart-type-form", ["chart_type", "widget_size", "map_selection"], null, null, false, function () {

        sendAjaxRequest("chart-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 = ["x_table", "x_axis_column", "date_range", "date_time_scale", "data_filter_columns", "y_table", "y_axis_column", "label", "function", "drill_down", "drill_down_columns"];
    $("#global-loader .loader-text").text("Wait while building your chart ...");

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

        if (window.parent) {
            window.parent.$('#edit-chart-modal').modal('hide');
            window.parent.reloadPagePartially("chart-search-form", ".charts", ".charts", true);


        }
        $("#global-loader .loader-text").text("");

    });

}
