Viewport.js 2.87 KB
/**
 * Controller: Viewport
 * 
 */
Ext.define('MyMA.controller.Viewport', {
    extend: 'Ext.app.Controller',
	views: ['Viewport', 'Authorize'], 
	refs: [{
		selector: 'viewport',
		ref: 'appView'
	}, {
		selector: 'authorize',
		ref: 'authPanel'
	}, {
		selector: 'authorize > form',
		ref: 'authForm'
	}],
	
	/**
	 * 
	 */
	isGuest: Ext.undefined,
	
	
	/**
	 * A template method that is called when your application boots. 
	 * It is called before the Application's launch function is executed so gives a hook 
	 * point to run any code before your Viewport is created.
	 */
    init: function(app) {
		// Bind Guest to the Ext.data.Connection
    	Ext.override(Ext.data.Connection, {
            /**
             * Set guest state to the authorization controller
             */
            setGuest: Ext.Function.bind(this.setGuest, this),
        
            /**
             * Return isGuest current value
             * @return {Boolean}
             */
            getGuest: Ext.Function.bind(this.getGuest, this)
    	});
		
    	this.control({
            'authorize > form > toolbar > button': {
                click: this.Authorize
            }
        });
    	
		this.Authorize();
    },
	
	
	/**
	 * Authorize
	 * if passed main application view, the first step need to query
	 * @param  object, main application view
	 */
	Authorize: function() {
		if (this.getAuthPanel()) {
            var form = this.getAuthPanel().down('form').getForm();
			if(form.isValid()) {
				form.submit({
					url: Ext.Ajax.getRestUrl('api','login', 'authorize', 0),
					method: 'PUT',
					clientValidation: true,
					scope: this,
					success: this.successLogin
				})
			}
		}
		else {
			Ext.Ajax.request({
				url: Ext.Ajax.getRestUrl('api', 'login'),
				scope: this,
				callback: function(){
					if (!this.isGuest && !this.getAppView()) {
                        this.setGuest(false);
						this.getView('Viewport').create();
					}
				}
			});
		}
	},

    /**
     * Return isGuest value
     * @param state
     */
    getGuest: function() {
        return this.isGuest;
    },

	
	/**
	 * Set isGuest flag value
	 * @param  object, this controller
	 * @param  boolean, state to set
	 */
	setGuest: function(state) {
		this.isGuest = Ext.isBoolean(state) ? state : true;

		if(this.isGuest && !this.getAuthPanel()) {
			this.getView('Authorize').create();
		}
	},
	
	
	/**
	 * private
	 */
	successLogin: function(form, action) {
		this.getAuthPanel().close();
		
		if(!this.getAppView()) {
			this.getView('Viewport').create();
		}
	},
	
	
	/**
	 * Logout
	 * public
	 */
	Logout: function() {
		Ext.Ajax.request({
            url: Ext.Ajax.getRestUrl('api','login', 'logout', 0),
            method: 'PUT',
			scope: this,
			callback: function() {
				if(this.getAppView()) {
					this.getController('Taskpanel').closeAll();
					this.getAppView().destroy();
				}
				this.setGuest(this, true);
			}
        });
	}
});