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

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

app.state.ConfigurationPrivacyEdit = function()
{
    var state = app.core.StateManager.createState( 'configuration-privacy-edit' );

    state.onEnter = function( p )
    {
        let $content = app.core.View.getContent(),
            groups = [],
            profile = null;

        app.gui.PageLoader.show();

        app.core.Rpc.call(
            'Account',
            'getAccountRelatedData',
            null,
            function( res )
            {
                profile = new app.model.Profile( res.profile );

                if ( res.own_teams && res.own_teams.length )
                {
                    for ( var ti = 0; ti < res.own_teams.length; ti++ )
                    {
                        groups.push( new app.model.Group( res.own_teams[ ti ] ) );
                    }
                }

                app.core.View.setContent(
                    app.core.View.getTemplate(
                        'configuration-privacy-edit',
                        {
                            p : profile,
                            groups : groups
                        }
                    )
                );

                $content.find( '[data-id="btn-save"]' ).first().click( function()
                {
                    var teamData = [];

                    app.gui.PageLoader.show();

                    $content.find( '[data-type="select-profile-visibility"]' ).each( function()
                    {
                        teamData.push({
                            teamId : $(this).attr( 'data-team-id' ),
                            isAnonymous : $(this).val()
                        });
                    });

                    app.core.Rpc.call(
                        'Profile',
                        'updatePrivacy',
                        {
                            teamData : teamData
                        },
                        function( res )
                        {
                            app.model.SessionUser.setUserProfile( new app.model.Profile( res.profile ) );
                            app.core.View.toastSuccess( _lc( 'NOTIFY_UPDATE_PRIVACY_SUCCESS' ) );
                            app.core.Controller.redirect( '#/configuration/privacy' );
                        }
                    );
                });

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

    return state;
};