Ext.ns('Nexts.module');

Nexts.module.LogoutModule = Ext.extend(Nexts.module.Module, {

	mtype: 'logout',

	id: 'Nexts.module.LogoutModule',
	
	cookieId: 'ticket',
	
	iconCls: 'ne-logoutmodule-icon',
	
	shortcutIconCls: 'ne-logoutmodule-shortcut',
	
	//url: 'logout.ac',
	
	//redirectUrl: '.',
	
	title: 'Logout',
	
	tooltip: '<b>Logout</b><br/>Close all applications and logout',
	
	confirmText: 'Are you sure you want to logout?',

	waitMsgText: 'Logout...',
	
	errorTitleText:	'ERROR',

	errorMsgText:	'Logout failed!',

	logoutConfirm: true,
	
	initModule: function() {
		this.addEvents('beforelogout', 'logout');

		Nexts.module.LogoutModule.superclass.initModule.call(this);
		
		this.app.logoutModule = this;
		
		this.on({
			beforelogout: this.app.beforeLogout,
			logout: this.app.onLogout,
			scope: this.app
		});
	},

	launchModule: function() {
		if (!this.inLogout) {
			this.inLogout = true;

			if (this.logoutConfirm) {
				Ext.Msg.confirm(this.title, this.confirmText, this.confirmCallback, this);
			}
			else {
				this.doLogout();
			}
		}
	},

	confirmCallback: function(btn) {
		if (btn == 'yes') {
			if (this.fireEvent('beforelogout') !== false) {
				this.doLogout();
				return;
			}
		}

		this.inLogout = false;
	},
	
	doLogout: function() {
		this.logoutMask = new Ext.LoadMask(Ext.getBody(), {
			msg: this.waitMsgText
		});

		this.logoutMask.show();

		if (this.url) {
			Ext.Ajax.request({
				url: this.url,
				success: this.onLogoutSuccess,
				failure: this.onLogoutFailure,
				scope: this
			});
		}
		else {
			this.onLogoutSuccess();
		}
	},

	clearAutoLogin: function() {
		try {
			var cs = String.decodeBase64(this.app.cookie.get(this.cookieId));
			var li = Ext.util.JSON.decode(cs);
			li.al = false;
			cs = Ext.util.JSON.encode(li);
			console.debug(cs);
			this.app.cookie.set(this.cookieId, String.encodeBase64(cs));
		}
		catch (ex) {
			console.error(ex);
		}
	},
	
	onLogoutSuccess: function(response, option) {
		this.clearAutoLogin();

		if (this.redirectUrl) {
			location.href = this.redirectUrl;
		}
		else {
			location.reload();
		}
		this.inLogout = false;
	},

	onLogoutFailure: function(response, option) {
		this.logoutMask.hide();
		this.logoutMask.destroy();
		delete this.logoutMask;

		Ext.Msg.show({
			title: this.errorTitleText,
			msg: this.errorMsgText,
			buttons: Ext.Msg.OK,
			icon: Ext.Msg.ERROR,
			fn: function() { this.inLogout = false; },
			scope: this
		});
		this.inLogout = false;
	}

});


