/**
 * (c) by aheadware.com
 */

var app = app || {};
app.state = app.state || {};

app.state.Home = function()
{
    var state = app.core.StateManager.createState( 'home', { filter: null } );

    state.createPager = function( allAppointments, currentPage )
    {
        var pageSize = 250,
            cPage = currentPage || 1;

        return {
            pageElements : allAppointments.slice( ((cPage-1) * pageSize), (cPage * pageSize )),
            totalElements : allAppointments.length,
            pageSize : pageSize,
            currentPage : cPage,
            totalPages : Math.ceil( allAppointments.length / pageSize )
        };
    };

    state.getMembersForAppointment = function( app, status )
    {
        let self = this,
            profileIds = [],
            appMembers = [],
            members = self.teamMembers.hasOwnProperty( app.getTeamId() ) ? self.teamMembers[ app.getTeamId() ] : [];

        switch( status )
        {
            case 'accepted':
                profileIds = app.getProfileIdsAccepted();
            break;

            case 'waiting':
                profileIds = app.getProfileIdsWaiting();
            break;

            case 'declined':
                profileIds = app.getProfileIdsDeclined();
            break;
        }

        for ( let pi = 0; pi < profileIds.length; pi++ )
        {
            for ( let mi = 0; mi < members.length; mi++ )
            {
                if ( profileIds[ pi ] == members[ mi ].getId() )
                {
                    //list += members[ mi ].getName();
                    appMembers.push( members[ mi ] );
                }
            }
        }

        return appMembers;
    };

    state.onEnter = function( p )
    {
        var $content = app.core.View.getContent(),
            appointments = [],
            allowedCategoryIds = [],
            gcgIds,
            userGroups = [],
            self = this,
            filter = this.getStateSetting( 'filter' ),
            isBackButton = app.core.StateManager.isPreviousState(),
            scrollY = +this.getStateSetting( 'scrollY' );

        // For paging
        self.currentPage = 1;
        self.appointments = appointments;

        self.teamMembers = {};

        app.gui.PageLoader.show();

        app.core.Rpc.call(
            'Profile',
            'get',
            {
                includeTeamMembers : true
            },
            function( res )
            {
                app.model.SessionUser.updateUserData( res.profile, res.profile_teams );

                userGroups = app.model.SessionUser.getGroups();

                for ( var ui = 0; ui < userGroups.length; ui++ )
                {
                    gcgIds = userGroups[ ui ].getCourseCategories();
                    for ( var gci = 0; gci < gcgIds.length; gci++ )
                    {
                        allowedCategoryIds.push( gcgIds[ gci ].id );
                    }
                }


                if ( !filter || !filter.hasOwnProperty( 'version' ) )
                {
                    filter = {
                        version : app.core.App.getVersion(),
                        previous : false,
                        appointmentCategoryIds : allowedCategoryIds,
                        disallowedCategoryIds : [],
                        isModified : false
                    };
                }
                else
                {
                    filter.appointmentCategoryIds = $( allowedCategoryIds ).not( filter.disallowedCategoryIds ).get();
                }

                // Set value of isModified
                if ( filter.previous || filter.disallowedCategoryIds.length )
                {
                    filter.isModified = true;
                }
                else
                {
                    filter.isModified = false;
                }

                function renderAppointmentItem( appointment )
                {
                    updateAppointment( appointment );
                    $content.find( '[data-type="appointment-item-container"][data-appointment-id="' + appointment.getId() + '"]' ).first().html(
                        app.core.View.getTemplate( 'home-appointment-item', { a : appointment } )
                    );
                }

                /**
                 *
                 * @param appointmentId
                 * @returns {*}
                 */
                function getAppointment( appointmentId )
                {
                    var app = null;

                    for ( var ai = 0; ai < appointments.length; ai++ )
                    {
                        if ( appointments[ ai ].getId() == appointmentId )
                        {
                            app = appointments[ ai ];
                            break;
                        }
                    }

                    return app;
                }

                /**
                 *
                 * @param appointment
                 */
                function updateAppointment( appointment )
                {
                    for ( var ai = 0; ai < appointments.length; ai++ )
                    {
                        if ( appointments[ ai ].getId() == appointment.getId() )
                        {
                            appointments[ ai ] = appointment;
                            break;
                        }
                    }
                }

                /**
                 * Render appointments according to pager setting
                 * @param pageNo
                 */
                function updatePaging( pageNo )
                {
                    var pager = self.createPager(
                            appointments,
                            +pageNo
                        ),
                        $content = app.core.View.getContent();

                    $content.html(
                        app.core.View.getTemplate(
                            'home',
                            {
                                appointments : pager.pageElements,
                                pager : pager,
                                filter : filter
                            }
                        )
                    );

                    // Animate scroll to top
                    $("html, body").animate({ scrollTop: 0 });
                }

                // Note
                // This needs to be called once at the beginning to trigger correct handlers and body classes
                app.core.View.setContent( 'Loading...' );

                for ( let teamId in res.profile_team_members )
                {
                    self.teamMembers[ teamId ] = [];
                    for ( let tmi = 0; tmi < res.profile_team_members[ teamId ].length; tmi++ )
                    {
                        self.teamMembers[ teamId ].push( new app.model.Profile( res.profile_team_members[ teamId ][ tmi ] ) );
                    }
                }

                app.core.Rpc.call(
                    'Appointment',
                    'getList',
                    {
                        filter: filter
                    },
                    function( res )
                    {
                        appointments = [];
                        for ( var ai = 0 ; ai <  res.appointments.length; ai++ )
                        {
                            appointments.push(
                                new app.model.Appointment(
                                    res.appointments[ ai ],
                                    res[ 'attendees_' + res.appointments[ ai ].id ]
                                )
                            );
                        }

                        self.appointments = appointments;

                        updatePaging();

                        $content.on( 'change', '[data-id="pager"]', function( e )
                        {
                            updatePaging( +$( this ).val() );
                        });

                        $content.on( 'click', '[data-type="appointment-short-info"]', function( e )
                        {
                            var $eTarget = $( e.target );
                            if ( $eTarget.attr( 'data-type') === 'appointment-rsvp-container'  ||
                                $eTarget.parents( '[data-type="appointment-rsvp-container"]' ).length )
                            {
                                return true;
                            }

                            var appId = $(this).attr( 'data-appointment-id' );
                            $content.find( '[data-type="appointment-detail-container"][data-appointment-id="' + appId + '"]' ).first().collapse( 'toggle' );
                        });

                        // start: News item action
                        $content.on( 'click', '[data-type="news-item"]', function( e )
                        {
                            var newsId = $(this).attr( 'data-news-id' );
                            $(this).find( '[data-type="news-collapse-icon"]' ).first().toggleClass( 'news-collapse-icon-rotate-down' );
                            $content.find( '[data-type="news-item-detail-container"][data-news-id="' + newsId + '"]' ).first().collapse( 'toggle' );
                        });
                        // stop: News item action


                        $content.on( 'click', '[data-type="btn-filter"]', function()
                        {
                            var p = {
                                title : _lc( 'HEADER_APPOINTMENT_FILTER' ),
                                body : app.core.View.getTemplate( 'home-modal-appointment-filter', { filter: filter, groups: app.model.SessionUser.getGroups()  } ),
                                onShow : function()
                                {
                                    var $modal = app.core.View.getModalContent();
                                },
                                onConfirm : function()
                                {
                                    var $modal = app.core.View.getModalContent(),
                                        newDisallowed = [];

                                    if ( $modal.find( '[data-id="filter-include-previous"]' ).first().is( ':checked') )
                                    {
                                        filter.previous = true;
                                    }
                                    else
                                    {
                                        filter.previous = false;
                                    }

                                    $modal.find( 'input[data-type="appointment-category"]:not(:checked )' ).each( function()
                                    {
                                        newDisallowed.push( $(this).val() );
                                    });

                                    filter.disallowedCategoryIds = newDisallowed;

                                    self.setStateSetting( 'filter', filter );
                                    app.core.Controller.reload();
                                    app.core.View.closeModal();
                                }
                            };
                            app.core.View.showModal( p );
                        });

                        $content.on( 'click', '[data-type="rsvp-button-recall"]', function()
                        {
                            var $btn = $(this),
                                appId = $btn.attr('data-appointment-id'),
                                $rsvpContainer = $content.find( '[data-type="appointment-rsvp-container"][data-appointment-id="' + appId + '"]' ).first(),
                                appointment = getAppointment(appId),
                                profileStatus = appointment.getAttendeeStatusForProfileId( app.model.SessionUser.getUserProfile().getId() );

                            if ( "accepted" !== profileStatus && "waiting" !== profileStatus )
                            {
                                return false;
                            }

                            app.core.View.confirm(
                                _lc( 'REALLY_RECALL_ATTENDEE_STATUS' ),
                                function()
                                {

                                    $rsvpContainer.find( '[data-type="section-rsvp-icon-accepted"]' ).first().hide();
                                    $rsvpContainer.find( '[data-type="section-rsvp-icon-waiting"]' ).first().hide();
                                    $rsvpContainer.find( '[data-type="section-rsvp-icon-loading"]' ).first().show();

                                    app.core.Rpc.call(
                                        'Appointment',
                                        'setAttendanceStatus',
                                        {
                                            appointmentId : appId,
                                            status : "declined"
                                        },
                                        function( res )
                                        {
                                            if ( false === res.hasOwnProperty( 'err' ) )
                                            {
                                                app.core.View.toastSuccess( _lc( 'SAVED' ) );
                                                renderAppointmentItem( new app.model.Appointment( res.appointment, res.attendee_data ) );
                                            }
                                            else if ( "deadline_over" === res.err )
                                            {
                                                app.core.View.toastError( _lc( 'DEADLINE_IS_OVER' ) );
                                                renderAppointmentItem( getAppointment( appId ) );
                                            }
                                            else if ( "deadline_reject_over" === res.err )
                                            {
                                                app.core.View.alert( _lc( 'DEADLINE_REJECT_IS_OVER' ) );
                                                renderAppointmentItem( getAppointment( appId ) );
                                            }
                                            else if ( "appointment_is_cancelled" === res.err )
                                            {
                                                app.core.View.alert( _lc( 'APPOINTMENT_IS_ALREADY_CANCELLED' ) );
                                                renderAppointmentItem( getAppointment( appId ) );
                                            }
                                            else if ( "appointment_not_accessible" === res.err )
                                            {
                                                app.core.View.toastSuccess( _lc( 'SAVED' ) );
                                                setTimeout( function()
                                                {
                                                    app.core.Controller.reload();
                                                }, 250 );
                                            }
                                            else
                                            {
                                                app.core.View.toastError( _lc( 'GENERAL_SERVER_ERROR' ) );
                                                renderAppointmentItem( getAppointment( appId ) );
                                            }
                                        }
                                    );
                                }
                            );
                        });

                        $content.on( 'click', '[data-type="rsvp-button-accept"]', function()
                        {
                            var $btn = $(this),
                                appId = $btn.attr('data-appointment-id'),
                                $rsvpContainer = $content.find( '[data-type="appointment-rsvp-container"][data-appointment-id="' + appId + '"]' ).first(),
                                appointment = getAppointment(appId),
                                profileStatus = appointment.getAttendeeStatusForProfileId( app.model.SessionUser.getUserProfile().getId() );

                            if ( "accepted" === profileStatus )
                            {
                                return false;
                            }

                            $rsvpContainer.find( '[data-type="section-rsvp-icon-unchecked"]' ).first().hide();
                            $rsvpContainer.find( '[data-type="section-rsvp-icon-loading"]' ).first().show();

                            app.core.Rpc.call(
                                'Appointment',
                                'setAttendanceStatus',
                                {
                                    appointmentId : appId,
                                    status : "accepted"
                                },
                                function( res )
                                {
                                    if ( false === res.hasOwnProperty( 'err' ) )
                                    {
                                        app.core.View.toastSuccess( _lc( 'SAVED' ) );
                                        renderAppointmentItem( new app.model.Appointment( res.appointment, res.attendee_data ) );
                                    }
                                    else
                                    {
                                        if ( res.err == 'max_reached' )
                                        {
                                            $rsvpContainer.find( '[data-type="section-rsvp-icon-loading"]' ).first().hide();
                                            $rsvpContainer.find( '[data-type="section-rsvp-icon-unchecked"]' ).first().show();

                                            app.core.View.confirm(
                                                _lc( 'MAX_REACHED_DO_YOU_WANT_ON_BE_ADDED_TO_THE_WAITLIST' ),
                                                function() {

                                                    $rsvpContainer.find( '[data-type="section-rsvp-icon-unchecked"]' ).first().hide();
                                                    $rsvpContainer.find( '[data-type="section-rsvp-icon-loading"]' ).first().show();

                                                    app.core.Rpc.call(
                                                        'Appointment',
                                                        'setAttendanceStatus',
                                                        {
                                                            appointmentId : appId,
                                                            status : 'waiting'
                                                        },
                                                        function( res )
                                                        {
                                                            var newAppointment = new app.model.Appointment( res.appointment, res.attendee_data );
                                                            app.core.View.toastWarning(
                                                                _lc(
                                                                    'SUCCESSFULLY_ADDED_TO_WAITING_LIST',
                                                                    [
                                                                        newAppointment.getWaitingPositionForProfileId( app.model.SessionUser.getUserProfile().getId() )
                                                                    ]
                                                                )
                                                            );
                                                            renderAppointmentItem( newAppointment );
                                                        }
                                                    );
                                                },
                                                _lc( 'BTN_OK' ),
                                            );
                                        }
                                        else if ( "deadline_over" === res.err )
                                        {
                                            app.core.View.toastError( _lc( 'DEADLINE_IS_OVER' ) );
                                            renderAppointmentItem( getAppointment( appId ) );
                                        }
                                        else
                                        {
                                            app.core.View.toastError( _lc( 'GENERAL_SERVER_ERROR' ) );
                                            renderAppointmentItem( getAppointment( appId ) );
                                        }
                                    }
                                },
                                function( res )
                                {
                                    renderAppointmentItem( getAppointment( appId ) );
                                }
                            );

                        });

                        $content.on( 'click', '[data-type="btn-appointment-edit"]', function()
                            {
                                var appToEdit = getAppointment( $(this).attr( 'data-appointment-id' ) );
                                if ( appToEdit.isSerial() )
                                {
                                    app.core.View.showModal({
                                        title : _lc( 'EDIT_SERIAL_APPOINTMENT' ),
                                        body : app.core.View.getTemplate( 'appointment-edit-modal-serial', { a : appToEdit } ),
                                        showOnlyCloseButton : true,
                                        onShow : function()
                                        {
                                            var $m = app.core.View.getModalContent();
                                            $m.find( '[data-id="btn-edit-single-appointment"]' ).first().click( function()
                                                {
                                                    app.core.View.closeModal();
                                                    app.core.Controller.redirect( '/#/appointment/edit/' + $(this).attr( 'data-appointment-id' ) )
                                                }
                                            );
                                            $m.find( '[data-id="btn-edit-serial-appointment"]' ).first().click( function()
                                                {
                                                    app.core.View.closeModal();
                                                    app.core.Controller.redirect( '/#/appointment/edit/' + $(this).attr( 'data-appointment-id' ) + '/serial' )
                                                }
                                            );
                                        }
                                    });
                                }
                                else
                                {
                                    app.core.Controller.redirect( '#/appointment/edit/' + appToEdit.getId() );
                                }
                            }
                        );

                        $content.on( 'click', '[data-type="btn-appointment-edit-attendee"]', function()
                        {
                            var appToEdit = getAppointment( $(this).attr( 'data-appointment-id' ) );
                            if ( appToEdit.isSerial() )
                            {
                                app.core.View.showModal({
                                    title : _lc( 'EDIT_SERIAL_APPOINTMENT' ),
                                    body : app.core.View.getTemplate( 'appointment-edit-modal-serial', { a : appToEdit } ),
                                    showOnlyCloseButton : true,
                                    onShow : function()
                                    {
                                        var $m = app.core.View.getModalContent();
                                        $m.find( '[data-id="btn-edit-single-appointment"]' ).first().click( function()
                                            {
                                                app.core.View.closeModal();
                                                app.core.Controller.redirect( '/#/appointment/edit/' + $(this).attr( 'data-appointment-id' ) + '/attendee' );
                                            }
                                        );
                                        $m.find( '[data-id="btn-edit-serial-appointment"]' ).first().click( function()
                                            {
                                                app.core.View.closeModal();
                                                app.core.Controller.redirect( '/#/appointment/edit/' + $(this).attr( 'data-appointment-id' ) + '/attendee/serial' );
                                            }
                                        );
                                    }
                                });
                            }
                            else
                            {
                                app.core.Controller.redirect( '#/appointment/edit/' + appToEdit.getId() + '/attendee' );
                            }
                        });

                        $content.on( 'click', '[data-type="btn-appoint-cancel"]', function()
                        {
                            var appointmentId = $(this).attr( 'data-appointment-id' );

                            app.core.View.confirm(
                                _lc( 'DO_YOU_REALLY_WANT_TO_CANCEL_APPOINTMENT' ),
                                function()
                                {
                                    app.core.Rpc.call(
                                        'Appointment',
                                        'cancel',
                                        {
                                            appointmentId : appointmentId
                                        },
                                        function( res )
                                        {
                                            app.core.View.toastSuccess( _lc( 'CANCEL_APPOINTMENT_SUCCESS' ) );
                                            app.core.Controller.reload();
                                        }
                                    );
                                },
                                _lc( 'BTN_CONFIRM_CANCEL_APPOINTMENT' )
                            );
                        });

                        $content.on( 'click', '[data-type="btn-appoint-delete"]', function()
                        {
                            var appointmentId = $(this).attr( 'data-appointment-id' );

                            var appToDelete = getAppointment( appointmentId );

                            if ( appToDelete.isDraft() && appToDelete.isSerial() )
                            {
                                app.core.View.showModal({
                                    title : _lc( 'DELETE_SERIAL_APPOINTMENT' ),
                                    body : app.core.View.getTemplate( 'appointment-delete-modal-serial', { a : appToDelete } ),
                                    showOnlyCloseButton : true,
                                    onShow : function()
                                    {
                                        var $m = app.core.View.getModalContent();
                                        $m.find( '[data-id="btn-delete-single-appointment"]' ).first().click( function()
                                            {
                                                app.gui.PageLoader.show();
                                                app.core.View.closeModal();
                                                app.core.Rpc.call(
                                                    'Appointment',
                                                    'delete',
                                                    {
                                                        appointmentId : appToDelete.getId(),
                                                        serialDeletion : false
                                                    },
                                                    function( res )
                                                    {
                                                        app.core.View.toastSuccess( _lc( 'DELETE_APPOINTMENT_SUCCESS' ) );
                                                        setTimeout( function()
                                                        {
                                                            app.core.Controller.reload();
                                                        }, 250 );
                                                    }
                                                );
                                            }
                                        );

                                        $m.find( '[data-id="btn-delete-serial-appointment"]' ).first().click( function()
                                            {
                                                app.gui.PageLoader.show();
                                                app.core.View.closeModal();
                                                app.core.Rpc.call(
                                                    'Appointment',
                                                    'delete',
                                                    {
                                                        appointmentId : appToDelete.getId(),
                                                        serialDeletion : true
                                                    },
                                                    function( res )
                                                    {
                                                        app.core.View.toastSuccess( _lc( 'DELETE_APPOINTMENT_SUCCESS' ) );
                                                        setTimeout( function()
                                                        {
                                                            app.core.Controller.reload();
                                                        }, 250 );
                                                    }
                                                );
                                            }
                                        );
                                    }
                                });
                            }
                            else
                            {

                                var warnTxt = '';
                                if ( true === appToDelete.hasContractAttendances() )
                                {
                                    warnTxt  = '<br /><br /><div class="alert alert-danger"><strong>Achtung:</strong> ';
                                    warnTxt += 'Dieser Termin wurde mit mindestens einem Mitglieder-Vertrag verrechnet. ';
                                    warnTxt += 'Diese Zuweisung ginge bei verloren.';
                                    warnTxt += '</div>';
                                }

                                app.core.View.confirm(
                                    _lc( 'DO_YOU_REALLY_WANT_TO_DELETE_APPOINTMENT' ) + warnTxt,
                                    function()
                                    {
                                        app.gui.PageLoader.show();
                                        app.core.Rpc.call(
                                            'Appointment',
                                            'delete',
                                            {
                                                appointmentId : appToDelete.getId()
                                            },
                                            function( res )
                                            {
                                                app.core.View.toastSuccess( _lc( 'DELETE_APPOINTMENT_SUCCESS' ) );
                                                setTimeout( function()
                                                {
                                                    app.core.Controller.reload();
                                                }, 250 );
                                            }
                                        );
                                    },
                                    _lc( 'BTN_CONFIRM_DELETE_APPOINTMENT' )
                                );
                            }

                        });

                        $content.on( 'click', '[data-type="btn-appoint-publish"]', function()
                        {
                            var appointmentId = $(this).attr('data-appointment-id'),
                                appToPublish = getAppointment( appointmentId );

                            if ( appToPublish.isDraft() && appToPublish.isSerial() )
                            {
                                app.core.View.showModal({
                                    title : _lc( 'PUBLISH_SERIAL_APPOINTMENT' ),
                                    body : app.core.View.getTemplate( 'appointment-publish-modal-serial', { a : appToPublish } ),
                                    showOnlyCloseButton : true,
                                    onShow : function()
                                    {
                                        var $m = app.core.View.getModalContent();
                                        $m.find( '[data-id="btn-publish-single-appointment"]' ).first().click( function()
                                            {
                                                app.gui.PageLoader.show();
                                                app.core.View.closeModal();
                                                app.core.Rpc.call(
                                                    'Appointment',
                                                    'publish',
                                                    {
                                                        appointmentId : appToPublish.getId(),
                                                        serialPublishing : false
                                                    },
                                                    function( res )
                                                    {
                                                        app.core.View.toastSuccess( _lc( 'APPOINTMENT_SUCCESSFULLY_PUBLISHED' ) );
                                                        setTimeout( function()
                                                        {
                                                            app.core.Controller.reload();
                                                        }, 250 );
                                                    }
                                                );
                                            }
                                        );

                                        $m.find( '[data-id="btn-publish-serial-appointment"]' ).first().click( function()
                                            {
                                                app.gui.PageLoader.show();
                                                app.core.View.closeModal();
                                                app.core.Rpc.call(
                                                    'Appointment',
                                                    'publish',
                                                    {
                                                        appointmentId : appToPublish.getId(),
                                                        serialPublishing : true
                                                    },
                                                    function( res )
                                                    {
                                                        app.core.View.toastSuccess( _lc( 'APPOINTMENT_SUCCESSFULLY_PUBLISHED' ) );
                                                        setTimeout( function()
                                                        {
                                                            app.core.Controller.reload();
                                                        }, 250 );
                                                    }
                                                );
                                            }
                                        );
                                    }
                                });
                            }
                            else
                            {
                                app.core.View.confirm(
                                    _lc('DO_YOU_REALLY_WANT_TO_PUBLISH_APPOINTMENT'),
                                    function () {
                                        app.gui.PageLoader.show();
                                        app.core.Rpc.call(
                                            'Appointment',
                                            'publish',
                                            {
                                                appointmentId : appToPublish.getId()
                                            },
                                            function( res )
                                            {
                                                app.core.View.toastSuccess( _lc( 'APPOINTMENT_SUCCESSFULLY_PUBLISHED' ) );
                                                setTimeout( function()
                                                {
                                                    app.core.Controller.reload();
                                                }, 250 );
                                            }
                                        );
                                    }
                                );
                            }

                        });

                        /*
                        if ( flag === "new-group-created" )
                        {
                            setTimeout( function()
                            {
                                app.core.View.showModal({
                                    title : _lc( 'WELCOME_TO_PROBUDDY' ),
                                    body : app.core.View.getTemplate( 'home-modal-welcome-trainer' ),
                                    showOnlyCloseButton : true,
                                    cancelButtonText : _lc( 'CLOSE' )
                                });
                            }, 500 );
                        }
                        else if ( flag === "new-member" )
                        {
                            setTimeout( function()
                            {
                                app.core.View.showModal({
                                    title: _lc('WELCOME_TO_PROBUDDY'),
                                    body: app.core.View.getTemplate('home-modal-welcome-member'),
                                    showOnlyCloseButton: true,
                                    cancelButtonText: _lc('CLOSE')
                                });
                            }, 500 );
                        }
                        */

                        if ( true === isBackButton )
                        {
                            setTimeout( function()
                            {
                                window.scrollTo( 0, scrollY);
                            }, 500 );
                        }
                        app.gui.PageLoader.hide();
                    }
                );

            }
        );
    };

    state.onExit = function( p )
    {
        this.setStateSetting( 'scrollY', window.scrollY );
    };

    return state;
};