jQuery(document).ready(function () {
    initDeleteAction();

    initDataTable();


alert('niche');
});

function initDeleteAction() {

    $('.action-delete').each(function (){
        $(this).on('click', function (e) {
            e.preventDefault();
            const id = $(this).parents('tr').first().data('id');

            $('#modal-delete').modal({backdrop: true, keyboard: true})
                .off('click', '#modal-delete-button')
                .on('click', '#modal-delete-button', function () {
                    let deleteForm = $('#delete-form');
                    deleteForm.attr('action', deleteForm.attr('action').replace('__id__', id));
                    deleteForm.trigger('submit');
                });
        });
    });
}


function initDataTable() {
    if ($(".table.datatable-simple").length > 0) {
        //$(".table.datatable-simple thead tr").clone(true).appendTo( '.table.datatable-simple tfoot' );

        $(".table.datatable-simple thead tr").clone(true).appendTo('.table.datatable-simple thead');
        $(".table.datatable-simple thead tr:eq(1) th").each(function (i) {
            if ($(this).data('searchable') == "input") {
                var title = $(this).text();
                var cssClass = '';
                if ($(this).text().trim().toLowerCase() == 'id') cssClass = 'small'
                $(this).html('<input type="text" placeholder="" class="datatable-field-search ' + cssClass + '" />');

                $('input', this).on('keyup change', function () {
                    if (this.value === "") {
                        $('.table.datatable-simple thead tr:eq(0) th:eq(' + i + ')').removeClass('filtered')
                    } else {
                        $('.table.datatable-simple thead tr:eq(0) th:eq(' + i + ')').addClass('filtered')
                    }
                    if (table.column(i).search() !== this.value) {
                        table
                            .column(i)
                            .search(this.value)
                            .draw();
                        var searchVal = this.value;
                        var body = $(table.table().body());

                        body.unhighlight();
                        body.highlight(searchVal);
                    }
                });
            }else if ($(this).data('searchable') == "date") {
                   /* var title = $(this).text();

                    $(this).html('<input type="date" class="datatable-field-date date-start" /> <input type="date" class="datatable-field-date date-end" /> ');

                    $dateStart = $(this).find('.date-start');
                    $dateEnd = $(this).find('.date-end');
                    $('input', this).on('keyup change', function () {
                        table.draw();
                    });

                    $.fn.dataTable.ext.search.push(
                        function( settings, data, dataIndex ) {
                            if($dateStart.val()!=="" || $dateEnd.val()!=="" ) {


                                var dateStart = parseInt(Date.parse($dateStart.val()));
                                var dateEnd = parseInt(Date.parse($dateEnd.val()));

                                currentDate = parseInt($('td.date').eq(dataIndex).find('time').data('timestamp'));
                                log(dateStart);
                                log(currentDate);
                                log($('td.date').eq(dataIndex));

                                return true;
                                if (((dateStart !== null && currentDate >= dateStart) || dateStart == null) && ((dateEnd !== null && dateEnd >= currentDate) || dateEnd == null)) {
                                    return true;
                                } else {
                                    return false;
                                }
                            }else{
                                return true;
                            }
                        }
                    );*/


                    /*$('input', this).on('keyup change', function () {
                        if (this.value === "") {
                            $('.table.datatable-simple thead tr:eq(0) th:eq(' + i + ')').removeClass('filtered')
                        } else {
                            $('.table.datatable-simple thead tr:eq(0) th:eq(' + i + ')').addClass('filtered')
                        }
                        if (table.column(i).search() !== this.value) {
                            table
                                .column(i)
                                .search(this.value)
                                .draw();
                            var searchVal = this.value;
                            var body = $( table.table().body() );

                            body.unhighlight();
                            body.highlight(searchVal);
                        }
                    });*/
            } else if ($(this).data('searchable') == 'select' ){
                $(this).html('<select  data-allow-clear="false"  class="list"><option value="all">Tout afficher</option></select>'); //LC_TRAD
            } else if ($(this).data('searchable') == 'select-text') {
                $(this).html('<select data-allow-clear="false" class="list-text"><option value="all">Tout afficher</option></select>'); //LC_TRAD
            } else {
                $(this).html('')
            }
        });

        var table = $(".table.datatable-simple").DataTable({
            orderCellsTop: true,
            pageLength: 50,
            fixedHeader: {
                header: true,
                headerOffset: $('.main-header').outerHeight(),
            },
            paging: true,
            //responsive: true,
            initComplete: function () {
                this.api().columns().every( function (i) {
                    var column = this;
                    var select = false;
                    if($('.table.datatable-simple thead tr:eq(1) th:eq('+i+') select.list-text').length) {
                        select = $('.table.datatable-simple thead tr:eq(1) th:eq(' + i + ') select.list-text');
                    }
                    if(select.length) {
                        column.data().unique().sort().each(function (d, j) {
                            values = d.split('\n');
                            for(k=0; k< values.length; k++) {
                                val = values[k];
                                select.append('<option value="' + val.trim() + '">' + val.trim() + '</option>')
                            }
                        });
                    }
                    if(!select) select = $('.table.datatable-simple thead tr:eq(1) th:eq('+i+') select.list')
                    if(select.length) {
                        column.data().unique().sort().each(function (d, j) {
                            $(d).each(function (k, val) {

                                select.append('<option value="' + $(val).text().trim() + '">' + $(val).text().trim() + '</option>')
                            });
                        });
                        setSelect2(select);
                        select.on( 'change', function () {
                            var val = $(this).val();
                            if(val=="all"){
                                $('.table.datatable-simple thead tr:eq(0) th:eq('+i+')').removeClass('filtered')
                                column.search('').draw();
                            }else {
                                $('.table.datatable-simple thead tr:eq(0) th:eq('+i+')').addClass('filtered')
                                column.search(val, false).draw();
                            }
                        } );
                    }
                } );
            },
            language: {
                "sEmptyTable":     "Aucune donnée disponible dans le tableau",
                "sInfo":           "Affichage de l'élément _START_ à _END_ sur _TOTAL_ éléments",
                "sInfoEmpty":      "Affichage de l'élément 0 à 0 sur 0 élément",
                "sInfoFiltered":   "(filtré à partir de _MAX_ éléments au total)",
                "sInfoPostFix":    "",
                "sInfoThousands":  ",",
                "sLengthMenu":     "Afficher _MENU_ éléments",
                "sLoadingRecords": "Chargement...",
                "sProcessing":     "Traitement...",
                "sSearch":         "Rechercher :",
                "sZeroRecords":    "Aucun élément correspondant trouvé",
                "oPaginate": {
                    "sFirst":    "Premier",
                    "sLast":     "Dernier",
                    "sNext":     "Suivant",
                    "sPrevious": "Précédent"
                },
                "oAria": {
                    "sSortAscending":  ": activer pour trier la colonne par ordre croissant",
                    "sSortDescending": ": activer pour trier la colonne par ordre décroissant"
                },
                "select": {
                    "rows": {
                        "_": "%d lignes sélectionnées",
                        "0": "Aucune ligne sélectionnée",
                        "1": "1 ligne sélectionnée"
                    }
                }
            },
        });
    }
}
