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

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

app.state.StatsPlanning = function()
{
    var state = app.core.StateManager.createState( 'stats-planning' );

    state.onEnter = function( p )
    {
        let $content = app.core.View.getContent(),
            groupId = p.groupId || null;

        app.gui.PageLoader.show();

        // Dummy code
        if ( null === groupId )
        {
            groupId = app.model.SessionUser.getGroups()[0].getId();
        }

        var selfApp = app;

        app.core.Rpc.call(
            'Stats',
            'getPlanning',
            {
                groupId : groupId
            },
            function( res )
            {
                selfApp.gui.PageLoader.hide();

                var numApps = 0,
                    numAttendances = 0,
                    memberTop10 = [],
                    avgAttendancePerAppointment = 0,
                    percentAttendantsToMembers = 0;

                var members = [],
                    member = null;
                for ( var mi = 0; mi < res.members.length; mi++ )
                {
                    member = new selfApp.model.Profile( res.members[ mi ] );
                    members.push( member );
                    memberTop10.push({
                        mem : member,
                        rank : 0,
                        numAttendances : 0
                    })
                }

                var apps = [],
                    attendantProfileIds = [],
                    appsTop10 = [];
                for ( var ai = 0; ai < res.apps.length; ai++ )
                {
                    apps.push(
                        new selfApp.model.Appointment(
                            res.apps[ ai ],
                            res[ 'attendees_' + res.apps[ ai ].id ]
                        )
                    );

                    appsTop10.push({
                        numAttendees : apps[ ai ].getNumAttendeesAccepted(),
                        app : apps[ ai ]
                    });

                    numAttendances += res[ 'attendees_' + res.apps[ ai ].id ].length;

                    for ( var aai = 0; aai < res[ 'attendees_' + res.apps[ ai ].id ].length; aai++ )
                    {
                        if ( -1 === attendantProfileIds.indexOf( '' + res[ 'attendees_' + res.apps[ ai ].id ][ aai ].profile_id ) )
                        {
                            attendantProfileIds.push( '' + res[ 'attendees_' + res.apps[ ai ].id ][ aai ].profile_id );
                        }
                        for ( var mai = 0; mai < memberTop10.length; mai++ )
                        {
                            if ( memberTop10[ mai ].mem.getId() == res[ 'attendees_' + res.apps[ ai ].id ][ aai ].profile_id )
                            {
                                memberTop10[ mai ].numAttendances++;
                                break;
                            }
                        }
                    }
                }

                memberTop10 = memberTop10.sort( selfApp.util.Helper.dynamicSort( '-numAttendances' ) );
                var mRank = 1,
                    mLastScore = 0;
                for ( let mri = 0; mri < memberTop10.length; mri++ )
                {
                    if ( memberTop10[ mri ].numAttendances < mLastScore )
                    {
                        mRank++;
                    }
                    memberTop10[ mri ].rank = mRank;
                    mLastScore = memberTop10[ mri ].numAttendances
                }

                appsTop10 = appsTop10.sort( selfApp.util.Helper.dynamicSort( '-numAttendees' ) );
                var rank = 1,
                    lastScore = 0;
                for ( let ri = 0; ri < appsTop10.length; ri++ )
                {
                    if ( appsTop10[ ri ].numAttendees < lastScore )
                    {
                        rank++;
                    }
                    appsTop10[ ri ].rank = rank;
                    lastScore = appsTop10[ ri ].numAttendees
                }


                var labels = [],
                    series = [],
                    day = null,
                    attendeesPerDay = 0,
                    moment7 = moment();//.subtract( 7, 'days' );

                for ( var i = 0; i < 7; i++ )
                {
                    moment7 = moment7.add( 1, 'days' );
                    day = moment7.format( 'DD.MM' );
                    labels.push( day );

                    attendeesPerDay = 0;
                    for ( var ii = 0; ii < apps.length; ii++ )
                    {
                        if ( day === apps[ ii ].getMomentStart().format( 'DD.MM' ) )
                        {
                            attendeesPerDay += apps[ ii ].getNumAttendeesAccepted();
                        }
                    }

                    series.push( attendeesPerDay );
                }

                numApps = apps.length;
                avgAttendancePerAppointment = numApps > 0 ? numAttendances / numApps : 0;
                percentAttendantsToMembers = members.length > 0 ? attendantProfileIds.length * ( 100 / members.length ) : 0;

                selfApp.core.View.setContent(
                    selfApp.core.View.getTemplate(
                        'stats-planning',
                        {
                            numApps : numApps,
                            numAttendances : numAttendances,
                            avgAttancePerAppointment : avgAttendancePerAppointment,
                            percentAttendantsToMembers : percentAttendantsToMembers,
                            groupId : groupId,
                            appsTop10 : appsTop10,
                            memberTop10 : memberTop10
                        }
                    )
                );

                $content.on( 'click', '[data-type="tr-app-row"]', function()
                {
                    selfApp.core.Controller.redirect( '#/appointment/' + $(this).attr( 'data-appointment-id' ) + '/attendee' );
                });

                $content.on( 'click', '[data-type="tr-member-row"]', function()
                {
                    selfApp.core.Controller.redirect( '#/group/' + groupId + '/membermanagement/' + $(this).attr( 'data-member-id' ) );
                });

                $content.find( '[data-id="select-team-id"]' ).on( 'change', function()
                {
                    selfApp.core.Controller.redirect( '#/stats/planning/' + $(this).val() );
                });

                var chartData = {
                    labels : labels,
                    series : [ series ]
                };

                var chartOptions = {
                    seriesBarDistance: 10,
                    fullWidth: true,
                    axisY : {
                        labelInterpolationFnc : function( value )
                        {
                            if ( value % 2 === 0 )
                            {
                                return value;
                            }
                            else
                            {
                                return '';
                            }
                        }
                    }
                };

                var responsiveOptions = [
                    ['screen and (max-width: 640px)', {
                        seriesBarDistance: 5,
                        fullWidth: true,
                        axisX: {
                            labelInterpolationFnc: function (value, i ) {
                                if ( i % 2 === 0 )
                                {
                                    return value.substr( 0, 3 );
                                }
                                else
                                {
                                    return '';
                                }
                            }
                        }
                    }]
                ];

                new Chartist.Bar('.ct-chart', chartData, chartOptions, responsiveOptions);

            }.bind( this )
        );
    };

    return state;
};
app.state.StatsPlanning.prototype.getBeforeValue = function( nowBefore )
{
    return '----';
};
