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

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

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

    state.onEnter = function( p )
    {
        let $authContent = app.core.View.getAuthContent();

        // Check local storage if a successful login process has taken place
        let hasLoggedInOnThisDeviceBefore = app.core.Cache.get( 'has-logged-in-on-this-device-before');

        // If yes, redirect to login
        if ( hasLoggedInOnThisDeviceBefore )
        {
            app.core.Controller.redirect( '#/auth/login' );
            return;
        }

        // Else show Group Join formular incl search
        app.gui.PageLoader.show();

        app.core.Rpc.call(
            'Auth',
            'getTeamsForJoin',
            null,
            function( res )
            {
                var teamData = res.teams,
                    $joinButton, selectedGroup,
                    $teamResultContainer = null;

                app.core.View.setAuthContent(
                    app.core.View.getTemplate( 'auth-start' )
                );

                $teamResultContainer = $authContent.find( '[data-id="container-group-result"]' ).first();
                $joinButton = $authContent.find( '[data-id="btn-select-team"]' ).first();

                $authContent.find( '[data-id="input-new-user-join-team-id"]' ).first().on( 'keyup', function()
                {
                    var groupId = $(this).val();

                    selectedGroup = null;

                    if ( groupId.length === 4 )
                    {
                        for ( var ti = 0; ti < teamData.length; ti++ )
                        {
                            if ( teamData[ ti ].public_id === groupId.toUpperCase() )
                            {
                                selectedGroup = teamData[ ti ];
                                break;
                            }
                        }
                    }

                    $teamResultContainer.html(
                        app.core.View.getTemplate(
                            'auth-start-group-result',
                            { selectedGroup: selectedGroup } )
                    );

                });

                $authContent.on( 'click', '[data-id="btn-select-team"]', function()
                {
                    if ( selectedGroup )
                    {
                        app.core.Controller.redirect( '#/auth/startjoin/' + selectedGroup.public_id );
                    }
                    return false;
                });
                app.gui.PageLoader.hide();

            }
            ,
            function( error )
            {

            }
        );
    };

    return state;
};