$(document).ready(function () {

    $('#add-widget-modal').on('hidden.bs.modal', function () {
        reloadForm("add-widget-form");
    });


    // edit widget modal
    $(document).on('click', "#add-widget-button", function () {
        let url = $(this).data('url');

        $.ajax({
            type: "GET",
            url: url,
            success: function (response) {
                $('#add-widget-modal-container').html(response);
                $('#add-widget-modal').modal('show');


                if ($(".demo-alert").length > 0) {
                    $("input[name=title]").on("keydown", function (e) {
                        e.preventDefault();
                        alertify.error("Available only in full version");
                        return false;
                    });

                    let dashboardResource = $("select#resource").val();

                    $("select#resource").on("change", function (e) {
                        e.preventDefault();
                        $(this).val(dashboardResource);

                        alertify.error("Available only in full version");
                        return false;
                    });
                    let dashboardResourceTypes = $("select#resource-types").val();

                    $("select#resource-types").on("change", function (e) {
                        e.preventDefault();
                        $(this).val(dashboardResourceTypes);

                        alertify.error("Available only in full version");
                        return false;
                    });



                    let dashboardIcon = $("select[name=dashboard_icon]").val();
                    $("select[name=dashboard_icon]").on("change", function (e) {

                        $(this).val(dashboardIcon);

                        alertify.error("Available only in full version");
                        return false;
                    });

                    $("#add-widget-form").on("click", "#saveBtn-add-widget", function () {

                        $("#add-widget-modal").modal('hide');
                    });



                } else {
                    $("#add-widget-form").on("click", "#saveBtn-add-widget", function () {

                        let fields = ["resource_type", "resource", "title"];
                        sendAjaxRequest("add-widget-form", fields, "add-widget-confirm", "add-widget-error", reloadHomePagePartially, [".home-parent-container", ".home-parent-container", true], true);

                    });


                }


            },
        });

    });



    $(document).on('change', "#resource-type", function (event) {
        if ($(`#${$(this).attr("id")} :selected`).val()) {
            let url = $(`#${$(this).attr("id")} :selected`).data("resource-types-url");
            let resourceType = $(`#${$(this).attr("id")} :selected`).text();
            let managementUrl = $(`#${$(this).attr("id")} :selected`).data("management-url");
            let managementSentence = getManagementSentence(resourceType);

            if (resourceType == "Report List") {
                $("#resource").attr("multiple", true);
                $("#resource").attr("name", "resource[]");
                $("#resource").find("option").get(0).remove();
                $("#report-list-container").show();
            } else {
                $("#resource").attr("multiple", false);
                $("#resource").attr("name", "resource");
                $("#report-list-container").hide();

            }

            $.ajax({
                type: "GET",
                url: url,
                contentType: false,
                processData: false,
                dataType: "json",
                beforeSend: function () {
                    $(".modal-spinner").fadeIn();
                    $('.modal-container').fadeOut();
                },
                success: function (response) {
                    updateSelectBox("resource", response.data.resources, true, response.data.can_add, managementUrl, managementSentence, resourceType, "Please Select Resource");
                    $(".modal-spinner").fadeOut();
                    $('.modal-container').fadeIn();

                }
            });


        }
    });

    $(document).on('change', "#resource", function (event) {
        if (window.parent) {
            if ($(this).val() == "add-new")
                window.parent.location.href = $('option:selected', this).data("url");
        }

    });


    $("#add-widget-form").on("click", "#saveBtn-add-widget", function () {

        let fields = ["resource_type", "resource", "title"];
        sendAjaxRequest("add-widget-form", fields, "add-widget-confirm", "add-widget-error", reloadHomePagePartially, [".home-parent-container", ".home-parent-container", true], true);

    });

    // delete widget modal
    $(document).on('click', ".delete-widget", function (event) {
        let widget = $(this).closest('.card-header').find('h3').text();
        $('#delete-widget-modal').find('.modal-body p').text(`Are you sure you want to delete this resource?`)
        $('#delete-widget-form').attr('data-url', $(this).attr('data-url'));
    });

    $("#delete-widget-form").on("click", "#saveBtn-delete-widget", function () {
        sendAjaxRequestWithSuccess("delete-widget-form", 'delete-widget-modal', reloadHomePagePartially, [".home-parent-container", ".home-parent-container", false], true);

    });

    // edit widget modal
    $(document).on('click', ".edit-widget", function () {
        let url = $(this).data('url');

        $.ajax({
            type: "GET",
            url: url,
            success: function (response) {
                $('#edit-widget-modal-container').html(response);
                $('#edit-widget-modal').modal('show');


                if ($(".demo-alert").length > 0) {
                    $("input[name=title]").on("keydown", function (e) {
                        e.preventDefault();
                        alertify.error("Available only in full version");
                        return false;
                    });

                    let dashboardResource = $("select#resource").val();

                    $("select#resource").on("change", function (e) {
                        e.preventDefault();
                        $(this).val(dashboardResource);

                        alertify.error("Available only in full version");
                        return false;
                    });

                    let dashboardResourceTypes = $("select#resource-types").val();

                    $("select#resource-types").on("change", function (e) {
                        e.preventDefault();
                        $(this).val(dashboardResourceTypes);

                        alertify.error("Available only in full version");
                        return false;
                    });


                    let dashboardIcon = $("select[name=dashboard_icon]").val();
                    $("select[name=dashboard_icon]").on("change", function (e) {

                        $(this).val(dashboardIcon);

                        alertify.error("Available only in full version");
                        return false;
                    });

                    $("#edit-widget-form").on("click", "#saveBtn-edit-widget", function () {
                        $("#edit-widget-modal").modal('hide');
                    });



                } else {

                    $("#edit-widget-form").on("click", "#saveBtn-edit-widget", function () {

                        let fields = ["resource_type", "resource", "title"];
                        sendAjaxRequest("edit-widget-form", fields, "edit-widget-confirm", "edit-widget-error", reloadPagePartially, [null, ".home-container", ".home-container"]);
                    });

                }
            },
        });

    });



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

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

        $.each(data, function (key, value) {
            $(`select[id="${id}"]`).append(
                '<option value="' + value.id + '">' + value.name + "</option>"
            );
        });
        if (showManagementUrl) {
            $(`select[id="${id}"]`).append(
                `<option value="add-new" data-url="${managementUrl}">${managementSentence}</option>`
            );

        }

    }

    function getManagementSentence(resourceType) {
        switch (resourceType) {
            case "Chart":
                return "+ Add new Chart"
                break;
            case "Metric / KPI":
                return "+ Add new Metric / KPI"
                break;
            case "Report List":
                return "+ Add new Report"
                break;
            default:
                break;
        }
    }

});
