/**
 * Created by aheadware
 */

"use strict";

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

/**
 *
 */
app.core.Session = (function(){

    var sessionData = null,
        session = null;
    return {
        destroy : function()
        {
            var hasLoggedInBefore = app.core.Cache.get( 'general.hasLoggedInBefore' );
            sessionData = null;
            session = null;
            app.model.SessionUser.destroy();
            app.core.Cache.clearAll();
            app.core.Cache.set( 'general.hasLoggedInBefore', hasLoggedInBefore );
        }
        ,
        getToken : function()
        {
            if ( session && session.token )
            {
                return session.token;
            }
            else
            {
                return null;
            }
        }
        ,
        getUserProfile : function()
        {
            return userProfile;
        }
        ,
        init : function( sessionData )
        {
            sessionData = sessionData || null;

            if ( null === sessionData )
            {
                // Try to retrieve from cache
                sessionData = app.core.Cache.get( 'sessionData' );
            }
            else
            {
                app.core.Cache.set( 'sessionData', sessionData );
            }

            if ( sessionData && sessionData.session )
            {
                session = sessionData.session;
            }

            if ( sessionData && sessionData.userProfile && sessionData.teams )
            {
                // Currently at this place - all login state stuff takes place
                app.model.SessionUser.init(
                    sessionData.userProfile,
                    sessionData.teams
                );
            }
        }
        ,
        isLoggedIn : function()
        {
            return ( session !== null );
        }
        ,
        hasLoggedInBefore : function()
        {
            return app.core.Cache.get( 'general.hasLoggedInBefore' );
        }

    };

})();