const CoronaTracking = {
    templateUrl : 'js/app/components/corona/corona-tracking.html',
    create : function( params )
    {
        const $container = $( this.container ),
              app = this.app,
              self = this;

        self.members = params.get( 'members' );
        self.apps = params.get( 'appointments' );

        this.render( { members: self.members } );

        $container.find( '[data-id="btnTrack"]' ).first().click( function()
        {
            const $form = $container.find( '[data-id="form-corona-tracking"]' ).first();
            let isValid = app.util.Form.bootstrapValidate( $form );

            if ( isValid )
            {
                const profileId = $form.find( '[name="profileId"]' ).first().val(),
                      dateFrom = $form.find( '[name="dateFrom"]' ).first().val(),
                      dateUntil = $form.find( '[name="dateUntil"]' ).first().val();
                self.update(
                    profileId,
                    moment( dateFrom, 'YYYY-MM-DD' ),
                    moment( dateUntil, 'YYYY-MM-DD' )
                );
            }
        });

        self.dp = $container.find( '[data-id="corona-tracking-result-datatable"]' ).first().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'
                },
            },
            buttons: [
                { extend: 'copy'},
                {extend: 'csv'},
                {extend: 'excel', title: 'Mitgliederliste'},
                {extend: 'pdf', title: 'Mitgliederliste'},

                {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');
                    }
                }
            ]

        });

    },

    update : function( profileId, momentFrom, momentUntil )
    {
        const newRows = [],
              self = this,
              memberList = {},
              apps = this.apps;

        let pid = '';
        for( let ai = 0; ai < apps.length; ai++ )
        {
            if ( "open" !== apps[ ai ].state ||
                 false === hasProfileIdAttended( profileId, apps[ ai ].attendees ) )
            {
                continue;
            }

            if ( apps[ ai ].getMomentOfStart().isBefore( momentFrom ) ||
                 apps[ ai ].getMomentOfStart().isAfter( momentUntil ) )
            {
                continue;
            }

            // Cast to string
            pid = '';

            for ( let i = 0; i < apps[ ai ].attendees.length; i++ )
            {
                pid = ('' + apps[ ai ].attendees[ i ].profile_id);
                if ( pid == profileId )
                {
                    continue;
                }

                if ( false === memberList.hasOwnProperty( pid ) )
                {
                    memberList[ pid ] = {
                        member : getMemberByProfileId( pid ),
                        count : 0
                    };
                }

                memberList[ pid ].count++;
            }
        }

        for ( let k in memberList )
        {
            newRows.push(
                [
                    ('' + k),
                    memberList[ k ].member ? memberList[ k ].member.getName() : '---',
                    memberList[ k ].member ? memberList[ k ].member.getAddress() : '---',
                    memberList[ k ].member ? memberList[ k ].member.getPhoneMobile() : '---',
                    ('' + memberList[ k ].count)
                ]
            )
        }

        self.dp.clear();
        self.dp.rows.add( newRows ).draw();

        function getMemberByProfileId( profileId )
        {
            let m = null;

            for ( let mi = 0; mi < self.members.length; mi++ )
            {
                if ( self.members[ mi ].id == profileId )
                {
                    m = self.members[ mi ];
                    break;
                }
            }

            return m;
        }

        function hasProfileIdAttended( profileId, attendees )
        {
            let hasAttended = false;

            if ( !attendees || 0 === attendees.length )
            {
                return hasAttended;
            }

            for( let ai = 0; ai < attendees.length; ai++ )
            {
                if ( attendees[ ai ].profile_id == profileId && attendees[ ai ].has_attended === "attended" )
                {
                    hasAttended = true;
                    break;
                }
            }

            return hasAttended;
        }
    },

    destroy : function()
    {

    }
};

export { CoronaTracking };