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

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

app.state.ConfigurationAccountEditAddress = function()
{
    var state = app.core.StateManager.createState( 'configuration-account-edit-address' );

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

        app.gui.PageLoader.show();

        app.core.Rpc.call(
            'Account',
            'getAccountRelatedData',
            null,
            function( res )
            {
                var profile = new app.model.Profile( res.profile, res.own_teams );
                app.core.View.setContent(
                    app.core.View.getTemplate(
                        'configuration-account-edit-address',
                        {
                            p : profile
                        }
                    )
                );

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

                    if (isValid)
                    {
                        app.gui.PageLoader.show();

                        app.core.Rpc.call(
                            'Profile',
                            'updateProfileAddress',
                            {
                                street : $form.find('[data-id="input-street"]').first().val(),
                                zipCode : $form.find('[data-id="input-zipcode"]').first().val(),
                                city : $form.find('[data-id="input-city"]').first().val(),
                                country : $form.find( '[data-id="input-country"]' ).first().val(),
                                mobile : $form.find('[data-id="input-mobile"]').first().val(),
                                phone : $form.find('[data-id="input-phone"]').first().val()
                            },
                            function( res )
                            {
                                if ( res && res.hasOwnProperty( 'profile' ) )
                                {
                                    app.model.SessionUser.setUserProfile( new app.model.Profile( res.profile) );
                                }
                                app.gui.PageLoader.hide();
                                app.core.View.toastSuccess( _lc( 'PROFILE_SUCCESSFULLY_UPDATED' ) );
                                app.core.Controller.redirect( '#/configuration/account' );
                            }
                        );

                    }
                });

                app.gui.PageLoader.hide();

            }
        );
    };

    return state;
};