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

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

app.state.AuthSso = function()
{
    var state = app.core.StateManager.createState( 'auth-sso' );

    state.onEnter = function( p )
    {
        var $authContent = app.core.View.getAuthContent(),
            redirect = app.core.Controller.getGetParam( "redirect" ),
            token = p.hasOwnProperty( 'token' ) ? p.token : null,
            theme = p.hasOwnProperty( 'theme' ) ? p.theme : null,
            bgImg = null;

        if ( token )
        {
            app.core.Rpc.call(
                'Auth',
                'sso',
                {
                    token : token
                },
                function(  res )
                {
                    if ( res && false === res.hasOwnProperty( 'error' ) )
                    {
                        app.core.Session.init( res );
                        if ( app.core.Session.isLoggedIn() )
                        {
                            app.core.Controller.disable();
                            if ( redirect )
                            {
                                app.core.Controller.redirect( '#' + redirect );
                            }
                            else
                            {
                                app.core.Controller.redirect( '#/home' );
                            }
                            app.core.Controller.reload( true );
                        }
                        else
                        {
                            onError();
                        }
                    }
                    else
                    {

                        onError();
                    }
                }
                ,
                function( err, code )
                {
                    onError();
                }
            );
        }
        else
        {
            onError();
        }

        function onError()
        {
            app.core.Controller.disable();
            app.core.Controller.redirect( '#/auth/login/' + theme );
            app.core.Controller.reload( true );
        }
    };

    return state;
};