const AppointmentSelectTable = {
    templateUrl : 'js/app/components/appointments/appointment-select-table.html',
    create : function( appointments )
    {
        var app = this.app,
            $container = $( this.container );

        let date = new Date();
        let strFrom = '';
        date.setMonth(date.getMonth() - 3);
        let dd = String(date.getDate()).padStart(2, '0');
        let mm = String(date.getMonth() + 1).padStart(2, '0'); //January is 0!
        let yyyy = date.getFullYear();
        strFrom = yyyy + '-' + mm + '-' + dd;

        date = new Date();
        let strTo = '';
        date.setMonth(date.getMonth() + 3);
        dd = String(date.getDate()).padStart(2, '0');
        mm = String(date.getMonth() + 1).padStart(2, '0'); //January is 0!
        yyyy = date.getFullYear();
        strTo = yyyy + '-' + mm + '-' + dd;

        let appointmentItems = appointments.getAll();

        this.render(
            { apps: appointmentItems,
              activeGroup : this.app.user.getActiveGroup(),
              strFrom: strFrom,
              strTo: strTo
            }
        );

        let table = $container.find( '.datatable' ).DataTable( {
            pageLength: 50,
            responsive: true,
            dom: '<"html5buttons"B>lTfgitp',
            language : {
                search      : 'Suche',
                emptyTable  : 'Keine Einträge vorhanden.',
                zeroRecords : 'Keine Einträge vorhanden.',
                info        : 'Zeige _START_ bis _END_ von _TOTAL_ Einträgen',
                lengthMenu : 'Zeige _MENU_ Einträge',
                paginate : {
                    first : 'Erste',
                    previous : 'Vorherige',
                    next : 'Nächste',
                    last : 'Letzte'
                },
            },
            /*
            columnDefs : [
                {
                    width : 180, targets : 10
                }
            ],*/
            buttons: [
                { extend: 'copy'},
                {extend: 'csv'},
                {extend: 'excel', title: 'Termine'},
                {extend: 'pdf', title: 'Termine'},

                {extend: 'print',
                    customize: function (win){
                        $(win.document.body).addClass('white-bg');
                        $(win.document.body).css('font-size', '10px');

                        $(win.document.body).find('table')
                            .addClass('compact')
                            .css('font-size', 'inherit');
                    }
                }
            ]
        });

        $container.on( 'click', 'tr[data-type="appointment"]', function()
        {
            $( this ).toggleClass( 'tr-selected' );
            //self.dispatchEvent( { type : 'selectionChanged', data : { selectedIds : self.getSelectedIds() } } );
        });

        $container.on( 'click', '[data-type="btn-edit-appointment"]', function( e )
        {
            app.openInApp( '/#/appointment/edit/' + $( this ).attr( 'data-appointment-id' ) );
            e.stopPropagation();
        });

        $container.on( 'click', '[data-type="btn-detail-appointment"]', function( e )
        {
            app.openInApp( '/#/appointment/' + $( this ).attr( 'data-appointment-id' ) );
            e.stopPropagation();
        });

        $container.on( 'click', '[data-type="btn-attendees-appointment"]', function( e )
        {
            app.openInApp( '/#/appointment/' + $( this ).attr( 'data-appointment-id' ) + '/attendee' );
            e.stopPropagation();
        });

        $container.on( 'click', '[data-type="btn-chat-appointment"]', function( e )
        {
            app.openInApp( '/#/appointment/' + $( this ).attr( 'data-appointment-id' ) + '/chat' );
            e.stopPropagation();
        });

        $('input.dateStart').on('change', function() {
            table.draw();
        });

        $('input.dateEnd').on('change', function() {
            table.draw();
        });

        // Add eventhandler for datepickers
        $.fn.dataTable.ext.search.push(
            function(settings, searchData, index, rowData, counter) {
                const dateFrom = $('input.dateStart').val();
                const dateTo = $('input.dateEnd').val();
                const item = appointmentItems[index];
                const startDate = item['start_dt'];
                const strStartDate = startDate.date.substring(0,10);

                if (dateFrom === '' && dateTo === '') {
                    return true;
                }
                if (dateFrom !== '' && dateTo === '') {
                    return strStartDate >= dateFrom;
                }
                if (dateFrom === '' && dateTo !== '') {
                    return strStartDate <= dateTo;
                }
                if (strStartDate >= dateFrom && strStartDate <= dateTo) {
                    return true;
                }
                return false;
            }
        );

        // Initial drawing needed to filter by date interval
        table.draw();
    },

    getSelectedIds : function()
    {
        let $container = $( this.container ),
            ids = [];

        $container.find( 'tr.tr-selected' ).each( function( i, v )
        {
            ids.push( $( this ).attr( 'data-appointment-id' ) );
        });

        return ids;
    },

    destroy : function()
    {
        // Remove eventhandler for datepickers
        $.fn.dataTable.ext.search.pop();
    }
};

export { AppointmentSelectTable };