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

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

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

    state.onEnter = function( p )
    {
        var $content = app.core.View.getContent(),
            self = this,
            group, members = [], appointments = [], currentProfile,
            groupId = p.groupId || null;

        app.gui.PageLoader.show();

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

        /**
         *
         * @param memberId
         * @returns {*}
         */
        function getMemberById( memberId )
        {
            var m = null;

            for ( var mi = 0; mi < members.length; mi++ )
            {
                if ( members[ mi ].getId() === memberId )
                {
                    m = members[ mi ];
                    break;
                }
            }

            return m;
        }

        /**
         *
         * @param memberId
         * @returns {string}
         */
        function getFirstName( memberId )
        {
            var firstName = 'Unbekannt',
                m = getMemberById( memberId );

            if ( m )
            {
                firstName = m.getFirstName();
            }

            return firstName;
        }

        /**
         *
         * @param memberId
         * @returns {string}
         */
        function getLastName( memberId )
        {
            var lastName = 'Unbekannt',
                m = getMemberById( memberId );

            if ( m )
            {
                lastName = m.getLastName();
            }

            return lastName;
        }

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

                app.core.Rpc.call(
                    'Team',
                    'getDetails',
                    {
                        teamId : groupId
                    },
                    function( res2 )
                    {
                        var member;
                        group = new app.model.Group( res2.team );

                        for ( var mi = 0; mi < res2.members.length; mi++ )
                        {
                            member = new app.model.Profile( res2.members[ mi ] );
                            members.push( member );
                            if ( member.getId() == app.model.SessionUser.getProfileId() )
                            {
                                currentProfile = member;
                            }
                        }

                        app.core.View.setContent(
                            app.core.View.getTemplate( 'stats-export', { groupId : groupId } )
                        );

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

                        // start: export
                        $content.find( '[data-id="btn-export"]' ).first().click( function()
                        {
                            var rows = [], config = {},
                                filename = group.getName() + "-" + moment().format( 'D-M-Y' );

                            //  Wann | Was | Wo | Vorname | Nachname | Status | Teilgenommen
                            rows.push(
                                [
                                    { value : 'Datum', type : 'string' },
                                    { value : 'Uhrzeit', type : 'string' },
                                    { value : 'Was', type : 'string' },
                                    { value : 'Wo', type : 'string' },
                                    { value : 'Terminstatus', type : 'string' },
                                    { value : 'Vorname', type : 'string' },
                                    { value : 'Nachname', type : 'string' },
                                    { value : 'Status', type : 'string' },
                                    { value : 'Status gesetzt durch', type : 'string' },
                                    { value : 'Teilgenommen', type : 'string' },
                                    { value : 'Vertrag', type: 'string' },
                                    { value : 'Vertragsdatum', type : 'string' }
                                ]
                            );

                            var attendees, status, hasAttended, member, contract, contractMoment,
                                appointmentStatus;
                            for ( var ai = 0; ai < appointments.length; ai++ )
                            {
                                attendees = appointments[ai].getAttendeeData();

                                if ( 0 === attendees.length ) continue;

                                appointmentStatus = appointments[ ai ].isCancelled() ? 'abgesagt' : 'stattgefunden';

                                for( var ati = 0; ati < attendees.length; ati++ )
                                {
                                    member = getMemberById( attendees[ ati ].profile_id );
                                    contract = null;
                                    contractMoment = null;

                                    status = "Unbekannt";
                                    hasAttended = "---";
                                    switch ( attendees[ ati ].status )
                                    {
                                        case "accepted":
                                            status = "zugesagt";
                                            break;

                                        case "declined":
                                            status = "abgesagt";
                                            break;

                                        case "waiting":
                                            status = "zugesagt (auf Warteliste)";
                                            break;
                                    }

                                    switch( attendees[ ati ].has_attended )
                                    {
                                        case "attended":
                                            hasAttended = appointments[ ai ].hasStarted() ? "Ja" : '---';
                                        break;

                                        default:
                                            hasAttended = appointments[ ai ].hasStarted() ? "Nein" : '---';
                                        break;
                                    }

                                    if ( member )
                                    {
                                        contract = member.getContractInGroup( groupId );
                                        contractMoment = member.getContractMomentInGroup( groupId );
                                    }

                                    rows.push([
                                        { value : appointments[ ai ].getMomentStart().format( 'DD.MM.YYYY'), type : 'string' },
                                        { value : appointments[ ai ].getMomentStart().format( 'HH:mm'), type : 'string' },
                                        { value : appointments[ ai ].getSubject(), type : 'string' },
                                        { value : appointments[ ai ].getLocation(), type : 'string' },
                                        { value : appointmentStatus, type : 'string' },
                                        { value : getFirstName( attendees[ ati ].profile_id ), type : 'string' },
                                        { value : getLastName( attendees[ ati ].profile_id ), type : 'string' },
                                        { value : status, type : 'string' },
                                        { value : getFirstName( attendees[ ati ].set_by_profile_id ) + ' ' + getLastName( attendees[ ati ].set_by_profile_id ), type : 'string' },
                                        { value : hasAttended, type : 'string' },
                                        { value : (contract ? contract : ''), type : 'string' },
                                        { value : (contractMoment ? contractMoment.format( 'DD.MM.YYYY' ) : ''), type : 'string' }
                                    ])
                                }
                            }

                            config.filename = filename;
                            config.sheet = { data : rows };
                            zipcelx( config );

                        });

                        app.gui.PageLoader.hide();


                    }
                );
            }
        );
    };

    return state;
};