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

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

app.state.GroupLeave = function()
{
    var state = app.core.StateManager.createState( 'group-leave' );

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

        app.gui.PageLoader.show();

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

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

                app.core.View.setContent(
                    app.core.View.getTemplate(
                        'group-leave',
                        {
                            group : group,
                            currentProfile : app.model.SessionUser.getUserProfile()
                        } )
                );

                $content.find( '[data-id="btn-leave-group"]' ).first().click( function()
                {
                    let $form = $content.find('[data-id="form-group-leave"]').first(),
                        isValid = app.util.Form.bootstrapValidate($form);

                    if (isValid)
                    {
                        app.gui.PageLoader.show();
                        app.core.Rpc.call(
                            'Team',
                            'leave',
                            {
                                groupId : group.getId()
                            },
                            function( res )
                            {
                                app.gui.PageLoader.hide();
                                app.core.Controller.disable();
                                app.core.Controller.redirect( '#/home' );
                                app.core.Controller.reload( true );
                            }
                        );
                    }
                });

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

    return state;
};