// define function
function limitless_init_datatable() {

    // counter for datatables
    let DatatableCounter = 0;

    // scann for each datatable
    $('.LimitlessTable').each(function () {

        // count table
        DatatableCounter++;

        // loading bar
        $(this).before('<div id="DatatableLoader' + DatatableCounter + '"><br/><center><b>[ LADE DATEN... ]</b></center><br/></div>');

    });

    setTimeout(function () {
        // reset counter for datatables
        let DatatableCounter = 0;

        // scann for each datatable
        $('.LimitlessTable').each(function () {

            // count table
            DatatableCounter++;

            // element
            let elementTable = $(this);

            let currentClass = elementTable.attr('class');
            currentClass = currentClass.replace('LimitlessTable','');

            // create replacement
            let NewHtml = '' +
                '<div id="DatatableFader' + DatatableCounter + '" class="DatatableFader">' +
                '<table id="Datatable' + DatatableCounter + '" class="display table datatable ' + currentClass + '">' +
                elementTable.html() +
                '</table>' +
                '</div>';

            // transport code to html
            elementTable.replaceWith(NewHtml);


            // render setup parameter
            let counter = 0;
            let sort = [];
            let orderable = [];

            $('#Datatable' + DatatableCounter).find('th').each(function () {

                let tableHeaderElement = $(this);

                // define sort
                if (tableHeaderElement.attr('Sort') != undefined) {
                    sort = [
                        [counter, tableHeaderElement.attr('Sort')]
                    ];
                }

                // orderable
                if (tableHeaderElement.attr('Sortable') == "false") {
                    orderable.push({
                        "orderable": false,
                        "targets": counter
                    });
                }

                // searchable
                if (tableHeaderElement.attr('Searchable') != undefined && tableHeaderElement.attr('Searchable') == "false") {
                    orderable.push({
                        "searchable": false,
                        "targets": counter
                    });
                }


                // counter
                counter++;
            });

            // rows
            let rows = elementTable.attr('rows');
            if (rows == undefined) {
                rows = 10;
            }

            // check entry count
            let Complex = false;
            if ($('#Datatable' + DatatableCounter).children('tbody').children('tr').length > rows) {
                Complex = true;
            }

            // export buttons
            let showExportButtons = elementTable.attr('exportable') != undefined && (elementTable.attr('exportable') == "true" || elementTable.attr('exportable') == true);
            let exportButtons = setExportButtons();

            // Define the table control elements to appear on the page and in what order.
            // https://datatables.net/reference/option/dom
            let dom = showExportButtons ?
                '<"datatable-header"fl><"datatable-scroll"t><"datatable-footer"Bip>' :
                '<"datatable-header"fl><"datatable-scroll"t><"datatable-footer"ip>';

            // length menu
            let lengthMenu = [
                [10, 25, 50, 100, 500, -1],
                ['Standard (10)', 25, 50, 100, 500, "Alle"]
            ];

            // activate datatable
            $('#Datatable' + DatatableCounter).dataTable({
                'dom': dom,
                "fixedHeader": true,
                'autoWidth': true,
                'pageLength': parseInt(rows),
                "order": sort,
                "paging": Complex,
                "searching": Complex,
                "info": Complex,
                "columnDefs": orderable,
                "buttons": exportButtons,
                "language": {
                    "search": '_INPUT_',
                    "searchPlaceholder": 'Suchen',
                    "lengthMenu": '<span>Einträge anzeigen</span> _MENU_',
                    "url": "//cdn.datatables.net/plug-ins/1.10.19/i18n/German.json",
                },
                "lengthMenu": lengthMenu,
                "drawCallback": function (settings) {

                    setSelect2();
                    animate(settings);

                }
            });
        });

    }, 300);
}

function animate(settings) {

    // calculate height for animation
    let height = $('#' + settings.sTableId).parents('.dataTables_wrapper').first().height() + 10;

    // get int from callback
    let callbbackid = settings.sTableId.replace(/[^\d.]/g, '');

    // remove loader
    $('#DatatableLoader' + callbbackid).remove();

    // break after inti
    if ($('#DatatableFader' + callbbackid).css("opacity") == 1) {
        return false;
    }

    // scale up table
    $('#DatatableFader' + callbbackid).animate({
        'opacity': '1',
        'min-height': height
    }, 300, function () {
        // fix height for responsible design
        $('#DatatableFader' + callbbackid).css("height", "auto");
        $('#DatatableFader' + callbbackid).css("min-height", "auto");
    });
}

// modified default class of export buttons.
// https://datatables.net/reference/option/buttons.dom.button
function setExportButtons() {

    return {
        dom: {
            button: {
                tag: 'button',
                className: ''
            }
        },
        buttons: [
            {
                extend: 'copy',
                className: 'btn btn-light'
            },
            {
                extend: 'csv',
                className: 'btn btn-light'
            },
            {
                extend: 'excel',
                className: 'btn btn-light'
            },
            {
                extend: 'pdf',
                className: 'btn btn-light'
            },
            {
                extend: 'print',
                className: 'btn btn-light'
            },
        ]
    };

}

// Select2 for length menu styling
function setSelect2() {

    if (!$().select2) {
        console.warn('Warning - select2.min.js is not loaded.');
        return;
    }

    // Initialize
    $('.dataTables_length select').select2({
        minimumResultsForSearch: Infinity,
        dropdownAutoWidth: true,
        width: 'auto'
    });
}


$(document).ready(function() {
    limitless_init_datatable();
});
