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

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

app.state.GroupMemberManagement = function()
{
    var state = app.core.StateManager.createState( 'group-member-management' );

    state.onEnter = function( p )
    {
        let $content = app.core.View.getContent(),
            fnRenderMemberForm = null,
            fnGetMemberById = null,
            fnUpdateMemberById = null,
            group = null,
            adminNoteXhr = null,
            playerHistoryXhr = null,
            memberToEdit = null,
            currentMember,
            members = [],
            groupId = p.groupId,
            memberId = p.hasOwnProperty( 'memberId' ) ? p.memberId : null;

        fnRenderMemberForm = function( profile )
        {
            $memberContainer = $content.find( '[data-id="member-container"]' ).first();
            $memberContainer.html(
                app.core.View.getTemplate(
                    'group-member-management-body',
                    {
                        p : profile,
                        g : group
                    }
                )
            );
        };

        fnUpdateAppointmentLog = function()
        {
            if ( !memberToEdit )
            {
                return;
            }

            if ( playerHistoryXhr )
            {
                playerHistoryXhr.abort();
            }

            playerHistoryXhr = app.core.Rpc.call(
                'Team',
                'getProfileAppointmentLog',
                {
                    groupId : group.getId(),
                    profileId : memberToEdit.getId(),
                    startDt : $content.find( '[data-id="input-appointment-log-from"]' ).first().val(),
                    endDt : $content.find( '[data-id="input-appointment-log-until"]' ).first().val()
                },
                function( res)
                {
                    $content.find( '[data-id="container-appointment-log"]' ).first().html(
                        app.core.View.getTemplate(
                            'group-member-management-body-appointment-log',
                            {
                                logs : res.appointmentLog
                            }
                        )
                    );
                },
                function()
                {
                    // Do nothing.
                }
            );
        };

        fnGetMemberById = function( profileId )
        {
            var p = null;

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

            return p;
        };

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

        fnUpdateMemberToEdit = function( mmid )
        {
            memberToEdit = fnGetMemberById( mmid );
            fnRenderMemberForm( memberToEdit );
            if ( memberToEdit )
            {
                if ( adminNoteXhr )
                {
                    adminNoteXhr.abort();
                }
                adminNoteXhr = app.core.Rpc.call(
                    'Team',
                    'getAdminNote',
                    {
                        groupId : group.getId(),
                        profileId : memberToEdit.getId()
                    },
                    function( res )
                    {
                        $content.find( '[data-id="admin-note"]' ).first().html(
                            app.core.View.getTemplate(
                                'group-member-management-body-adminnote',
                                {
                                    adminNote : res.adminNote ? res.adminNote : ''
                                }
                            )
                        );
                    },
                    function()
                    {
                        // Do nothing
                    }
                );
            }
            fnUpdateAppointmentLog();
        };

        app.gui.PageLoader.show();

        app.core.Rpc.call(
            'Team',
            'getDetails',
            { teamId : groupId, includeEmails : true },
            function( res )
            {

                var member = null,
                    $memberContainer = null,
                    emails = res.emails ? res.emails : [];

                group = new app.model.Group( res.team );

                for ( var mi = 0; mi < res.members.length; mi++ )
                {
                    member = new app.model.Profile( res.members[ mi ] );
                    for ( var ei = 0; ei < emails.length; ei++ )
                    {
                        if ( member.getAccountId() == emails[ ei ].id )
                        {
                            member.setEmail( emails[ ei ].email );
                            break;
                        }
                    }
                    members.push( member );
                    if ( member.getId() == app.model.SessionUser.getProfileId() )
                    {
                        currentProfile = member;
                    }
                }

                app.core.View.setContent(
                    app.core.View.getTemplate(
                        'group-member-management',
                        {
                            members : members,
                            group : group,
                            groups : app.model.SessionUser.getAdminGroups(),
                            currentProfile : currentProfile
                        } )
                );

                $content.find( '[data-id="select-group-id"]' ).first().change( function()
                {
                    app.core.Controller.redirect( '#/group/' + $(this).val() + '/membermanagement' );
                });

                $content.on( 'click', '[data-id="btn-update-role"]', function()
                {
                    var newRole = $content.find( '[data-id="select-member-role"]' ).first().val();
                    if ( memberToEdit.getRoleInGroup( group.getId() ) === newRole )
                    {
                        return;
                    }
                    app.gui.PageLoader.show();
                    app.core.Rpc.call(
                        'Team',
                        'changeMemberRole',
                        {
                            groupId : group.getId(),
                            memberId : memberToEdit.getId(),
                            newRole : newRole
                        },
                        function( res )
                        {
                            app.core.View.toastSuccess( _lc( 'MEMBER_ROLE_CHANGED' ) );
                            if ( app.model.SessionUser.isOwnProfile( memberToEdit ) )
                            {
                                app.core.Controller.redirect( '#/group/' + group.getId() );
                            }
                            app.gui.PageLoader.hide();
                        }
                    );
                });

                $content.on( 'click', '[data-id="btn-update-contract"]', function()
                {
                    var contractUnix = null;

                    if ( $content.find( '[data-id="input-contract-moment"]' ).first().val().length )
                    {
                        contractUnix = app.util.Helper.getMomentFromInputDate( $content.find( '[data-id="input-contract-moment"]' ).first() ).unix();
                    }

                    app.gui.PageLoader.show();
                    app.core.Rpc.call(
                        'Team',
                        'changeMemberContract',
                        {
                            groupId : group.getId(),
                            memberId : memberToEdit.getId(),
                            contract : $content.find( '[data-id="input-contract"]' ).first().val(),
                            contractDate : contractUnix
                        },
                        function( res )
                        {
                            app.core.View.toastSuccess( _lc( 'MEMBER_CONTRACT_UPDATED' ) );
                            app.gui.PageLoader.hide();
                            if ( res && res.hasOwnProperty( 'updated_member' ) )
                            {
                                memberToEdit.setGroupData( res.updated_member.teams_js );
                            }
                        }
                    );
                });

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

                $content.on( 'click', '[data-id="btn-update-appointment-log"]', function()
                {
                    app.core.View.setContentLoader(
                        $content.find( '[data-id="container-appointment-log"]' ).first()
                    );
                    fnUpdateAppointmentLog();
                });

                $content.on( 'click', '[data-id="btn-save-admin-note"]', function()
                {
                    app.gui.PageLoader.show();
                    app.core.Rpc.call(
                        'Team',
                        'updateAdminNote',
                        {
                            groupId : group.getId(),
                            profileId : memberToEdit.getId(),
                            adminNote : $content.find( '[data-id="textarea-admin-note"]' ).first().val()
                        },
                        function()
                        {
                            app.core.View.toastSuccess( _lc( 'ADMIN_NOTE_SAVED' ) );
                            app.gui.PageLoader.hide();
                        }
                    );

                    $content.find( '[data-id=""]' ).first().val()
                });

                $content.find( '[data-id="select-profil-id"]' ).first().change( function()
                {
                    app.core.Controller.redirect( '#/group/' + group.getId() + '/membermanagement/' + $(this).val() );
                });

                $content.find( '[data-id="btn-remove-member"]' ).first().click( function()
                {
                    if ( !memberToEdit )
                    {
                        app.core.View.toastInfo( _lc( 'PLEASE_SELECT_MEMBER' ) );
                        return;
                    }

                    if ( 'trainer' == memberToEdit.getRoleInGroup( group.getId() ) )
                    {
                        app.core.View.toastInfo( _lc( 'GROUP_OWNER_CANNOT_BE_REMOVED_FROM_GROUP' ) );
                        return;
                    }

                    app.core.View.confirm(
                        _lc( 'DO_YOU_REALLY_WANT_TO_REMOVE_THIS_MEMBER_FROM_TEAM' ),
                        function()
                        {
                            app.gui.PageLoader.show();
                            app.core.Rpc.call(
                                'Team',
                                'removeMember',
                                {
                                    groupId : group.getId(),
                                    profileId : memberToEdit.getId()
                                },
                                function( res )
                                {
                                    app.core.Controller.redirect( '#/group/' + group.getId() + '/members'  );
                                    app.core.View.toastSuccess( _lc( 'MEMBER_REMOVED' ) );
                                }
                            );
                        },
                        _lc( 'YES_REMOVE' )
                    );
                });

                fnRenderMemberForm( null );

                if ( memberId )
                {
                    $content.find( '[data-id="select-profil-id"]' ).first().val( memberId );
                    $content.find( '[data-id="select-profil-id"]' ).first().trigger( 'change' );
                    fnUpdateMemberToEdit( memberId )
                }

                app.gui.PageLoader.hide();
            }
        );
    };

    return state;
};