/**
 * Project  : AMDA-NG4
 * Name     : AmdaApp.js
 * @class   amdaApp.AmdaApp
 * @extends Ext.ux.desktop.App
 * @brief   Main class defining Amda Desktop and its Modules
 * @author  Ext JS Library 4.0 Copyright(c) 2006-2011 Sencha Inc. licensing@sencha.com
 */

Ext.define('amdaApp.AmdaApp', {
	extend: 'Ext.ux.desktop.App',

	requires: [
		'Ext.window.MessageBox',
		'Ext.ux.desktop.ShortcutModel',
		'amdaUI.SampToolBarUI',
		'amdaDesktop.DynamicModule',
		'MyDesktop.Settings'
	],

	dynamicModules: {
		visu : {
				id          : 'visu-win',
				icon        : 'icon-visu_catalog',
				title       : 'Visualization',
				source      : 'amdaDesktop.VisuModule',
				useLauncher : true
			},
		statistics : {
				id          : 'statistics-win',
				icon        : 'icon-statistics',
				title       : 'Statistics',
				source      : 'amdaDesktop.StatisticsModule',
				useLauncher : true
			},
		catalog : {
				id          : 'catalog-win',
				icon        : 'icon-catalog',
				title       : 'Manage catalogs',
				source      : 'amdaDesktop.CatalogModule',
				useLauncher : true
			},
		param : {
			id          : 'param-win',
			icon        : 'icon-parameters',
			title       : 'Create/modify parameters',
			source      : 'amdaDesktop.ParameterModule',
			useLauncher : true
		},
		tt : {
			id          : 'timetab-win',
			icon        : 'icon-manage-tt',
			title       : 'Manage Time Tables',
			source      : 'amdaDesktop.TimeTableModule',
			useLauncher : true
		},
		tt_op : {
			id          : 'ttsOpe-win',
			icon        : 'icon-tts',
			title       : 'Operations on Time Tables',
			source      : 'amdaDesktop.TimeTableOperationModule',
			useLauncher : true
		},
		plot : {
			id          : 'plot-win',
			icon         : 'icon-plot',
			title       : 'Plot Manager',
			source      : 'amdaDesktop.PlotModule',
			useLauncher : true
		},
		search : {
			id          : 'search-win',
			icon        : 'icon-search',
			title       : 'Data Mining',
			source      : 'amdaDesktop.SearchModule',
			useLauncher : true
		},
		download : {
			id          : 'down-win',
			icon        : 'icon-download',
			title       : 'Download data',
			source      : 'amdaDesktop.DownloadModule',
			useLauncher : true
		},
		upload : {
			id          : 'up-win',
			icon        : 'icon-mydata',
			title       : 'Upload data',
			source      : 'amdaDesktop.UploadModule',
			useLauncher : true
		},
		interop : {
			id          : 'interop-win',
			icon        : 'icon-interop',
			title       : 'Interoperability',
			source      : 'amdaDesktop.InteropModule',
			useLauncher : true
		},
		epntap : {
			id          : 'epntap-win',
			icon        : 'icon-interop',
			title       : 'EPN-TAP data',
			source      : 'amdaDesktop.EpnTapModule',
			useLauncher : false
		},
		info : {
			id          : 'info-win',
			icon        : 'icon-information',
			title       : 'About AMDA',
			source      : 'amdaDesktop.AboutModule',
			useLauncher : false
		},
		explorer : {
			id          : 'explorer-win',
			icon        : 'icon-elements',
			title       : 'Workspace Explorer',
			source      : 'amdaDesktop.ExplorerModule',
			useLauncher : false
		},
		my_data : {
			id          : 'mydata-win',
			icon        : 'icon-mydata',
			title       : 'Define parameter',
			source      : 'amdaDesktop.MyDataModule',
			useLauncher : false
		},
		help : {
			id          : 'help-win',
			icon        : 'icon-help',
			title       : 'Help',
			source      : 'amdaDesktop.HelpModule',
			useLauncher : false
		},
		feedback : {
			id          : 'feed-win',
			icon        : 'icon-feedback',
			title       : 'Feedback',
			source      : 'amdaDesktop.FeedbackModule',
			useLauncher : false
		},
		filters : {
			id          : 'filters-win',
			icon        : 'icon-filter',
			title       : 'Filters',
			source      : 'amdaDesktop.FiltersModule',
			useLauncher : false
		},
		result : {
			id          : 'result-win',
			contentId   : 'resultUI',
			icon        : 'icon-results',
			title       : 'Results',
			source      : 'amdaDesktop.ResultModule',
			useLauncher : false
		},
		astro : {
			id          : 'astroimages-win',
			icon        : 'icon-interop',
			title       : 'Astronomical Images',
			source      : 'amdaDesktop.AstroImagesModule',
			useLauncher : false
		}
	},

	// IDs of Modules working with  parameters; used in Alias Node
	//TODO stats-win
	paramModulesID : ['plot-win', 'param-win', 'search-win', 'down-win'],

	// Important system constants
	MAX_UPLOADED_FILE_SIZE : max_uploaded_file_size, // in B, from my_config.php

	listeners : {
		scope : this,
		beforeunload : function ()
		{
			var interopModule = myDesktopApp.getLoadedModule(myDesktopApp.dynamicModules.interop.id);
			if (interopModule)
				interopModule.forceSampDisconnect();
			return true;
		},
		ready : function ()
		{
			AmdaAction.cleanUserWS(function(res,e){},this);
		}
	},

	init: function() 
	{
		// custom logic before getXYZ methods get called...
		this.callParent();
		
		// now ready...
		//override createWindow method of desktop
		Ext.override(Ext.ux.desktop.Desktop, {
			createWindow: function (config, cls) {
				var me = this;
				var win = this.callParent([config,cls]);
				win.on({
					boxready: function (w) {
						w.dd.xTickSize = me.xTickSize;
						w.dd.yTickSize = me.yTickSize;

						if (w.resizer) {
								w.resizer.widthIncrement = me.xTickSize;
								w.resizer.heightIncrement = me.yTickSize;
						}

						if (w.y < 0)
								w.el.setY(0);

						if (w.x + w.width > me.el.getWidth())
								w.el.setX(me.el.getWidth()-w.width);

						if (w.y + w.height > me.el.getHeight())
								w.el.setY((me.el.getHeight()-w.height > 0) ? me.el.getHeight()-w.height : 0);

					},
					single: true
				});
				return win;
			}
		});
	},
	
	//create InfoBox
	infoMsg : function(msg) {
		Ext.Msg.show({
			title: 'AMDA Info',
			cls: 'infoMsg',
			msg: msg,
			modal: false,
			autoScroll: true,
			resizable: true,
			icon: Ext.Msg.INFO,
			buttons: Ext.Msg.OK
		});
	},
	//create InfoBox
	infoMsgLong : function(msg) {
		Ext.Msg.show({
			title: 'AMDA Info',
			cls: 'infoMsgLong',
			msg: msg,
			modal: false,
			autoScroll: true,
			resizable: true,
			icon: Ext.Msg.INFO,
			buttons: Ext.Msg.OK
		});
	},
	//create WarningBox
	warningMsg : function(msg) {
		Ext.Msg.show({
			title: 'Attention',
			msg: msg,
			icon: Ext.Msg.WARNING,
			buttons: Ext.Msg.OK
		});
	},

	//create ErrorBox
	errorMsg : function(msg) {
		Ext.Msg.show({
			title: 'Failure',
			msg: msg,
			icon: Ext.Msg.ERROR,
			buttons: Ext.Msg.OK
		});
	},

	// add info icon; onCick AmdaHelp is shown
	addAmdaInfo : function(help, style) {
		if (style) {
			help +=  '" style="' + style;
		}
		var html =  '<img amda_clicktip="' + help + '" src="js/resources/images/16x16/info_mini.png"'
		return {
			xtype: 'label',
			html: html,
			listeners: {
				click: {
					element: 'el',
					fn: function(e,t) { 
						var me = t,
						text = me.getAttribute('amda_clicktip');
						if (text) {
							e.preventDefault();
							AmdaAction.getInfo({name : text}, function(res,e) {
								if (res.success) myDesktopApp.infoMsg(res.result);
							}); 
						}
					}
				}
			}
		};
	},

	getModules : function(){
		var allModules = [];

		//Add dynamic modules
		Ext.Object.each(this.dynamicModules, function(key, def) {
			allModules.push(new amdaDesktop.DynamicModule(def.id, def.icon, def.title, def.source, def.useLauncher));
		});

		return allModules;
	},

	getDesktopConfig: function () 
	{
		var me = this, ret = me.callParent();

		var desktopId = 'AmdaDesktop';
		var wallpaper = Ext.state.Manager.getProvider().get(desktopId+'_wallpaper');
		if (!wallpaper)
				wallpaper = 'js/resources/images/desktop/wallpapers/Cdpp2.jpg';
		return Ext.apply(ret, {
			id       : desktopId,
			contextMenuItems: [
					{ text: 'Change Settings', handler: me.onSettings, scope: me }
			],
			shortcuts: Ext.create('Ext.data.Store', {
				model: 'Ext.ux.desktop.ShortcutModel',
				data: [
					{ name: 'Help',  iconCls: 'help', module: 'help-win' },
					{ name: 'Create/Modify parameter',  iconCls: 'edit', module: 'param-win' },
					{ name: 'Plot data',  iconCls: 'plot', module: 'plot-win'},
					{ name: 'Data mining',  iconCls: 'search', module: 'search-win'},
					{ name: 'Statistics',  iconCls: 'statistics', module: 'statistics-win'},
					{ name: 'Download data',  iconCls: 'download_manager', module: 'down-win'},
					{ name: 'Upload data',  iconCls: 'mydata', module: 'up-win'},
					{ name: 'Manage TimeTables',    iconCls: 'timeTable', module: 'timetab-win' },
					{ name: 'TimeTables operations',   iconCls: 'operations', module: 'ttsOpe-win' },
					{ name: 'Manage catalogs',  iconCls: 'catalog', module: 'catalog-win'},
					{ name: 'Visualize catalogs',  iconCls: 'visu_catalog', module: 'visu-win'},
					{ name: 'Interoperability',   iconCls: 'interop', module: 'interop-win' }
				]
			}),

			wallpaper: wallpaper,
			wallpaperStretch: false
		});
	},

	// config for the start menu
	getStartConfig : function() 
	{
		var me = this, ret = me.callParent();
		return Ext.apply(ret, {
			title: sessionID,
			iconCls: 'icon-user',
			height: 270,
			toolConfig: {
				width: 130,
				items: [
					{
						text:'Settings',
						iconCls:'settings',
						handler: me.onSettings,
						scope: me
					}, '-',
					{
						text : 'Profile',
						iconCls : 'icon-user',
						id : 'profile-win-tool',
						handler : function(obj, e) {
								e.stopEvent();
								AmdaAction.getUserInfo(this.onGetUserInfo,this);
						},
						scope : this
					},
					{
						text : 'Feedback',
						iconCls : 'icon-feedback',
						id : 'feed-win-tool',
						handler : function(obj, e) {
								e.stopEvent();
								var moduleId = obj.el.id;
								this.getLoadedModule(moduleId.replace('-tool', ''), true, function(module) {
								module.createWindow();
								});
						},
						scope : this
					}, 
					{
						text : 'Help',
						iconCls : 'icon-help',
						id : 'help-win-tool',
						scope : this,
						handler : function(obj, e) {
								e.stopEvent();
								var moduleId = obj.el.id;
								this.getLoadedModule(moduleId.replace('-tool', ''), true, function(module) {
								module.createWindow();
							});
						}
					}, 
					{
						text : 'About AMDA',
						iconCls : 'icon-information',
						id : 'info-win-tool',
						scope : this,
						handler : function(obj, e) {
								e.stopEvent();
								var moduleId = obj.el.id;
								this.getLoadedModule(moduleId.replace('-tool', ''), true, function(module) {
								module.createWindow();
								});
						}
					}, '-', 
					{
						text : 'Workspaces',
						iconCls : 'icon-ws',
						disabled: true,
						scope : this
					}, '-', 
					{
						text : 'Logout',
						iconCls : 'logout',
						scope : this,
						handler : me.onLogout
					}
				]
			}
		});
	},

	getModuleDefinition: function(id) {
		return this.getModule(id);
	},

	getLoadedModule: function(id, forceLoad, onReady) {
		var moduleDef = this.getModuleDefinition(id);
		if (!moduleDef)
			return null;
		if (!moduleDef.isReady())
		{
			if (forceLoad)
			{
				//loadMask.show();
				moduleDef.get(function (module) {
					//loadMask.hide();
					if (onReady)
						onReady(module);
				});
			}
			return null;
		}
		if (onReady)
			onReady(moduleDef.get());
		return moduleDef.get();
	},

	getTaskbarConfig: function () 
	{
		var ret = this.callParent();
		return Ext.apply(ret, {
			quickStart: [],
			trayItems: [
				{
					name: this.dynamicModules.feedback.title, iconCls: 'icon-feedback',
					tooltip: { text: this.dynamicModules.feedback.title, align: 'bl-tl' },
					overflowText: this.dynamicModules.feedback.title,
					iconCls: this.dynamicModules.feedback.icon,
					scope: this,
					handler : function(obj, e) {
						e.stopEvent();
						this.getLoadedModule(this.dynamicModules.feedback.id, true, function(module) {
								module.createWindow();
						});
					}
				},
				{
					name: this.dynamicModules.info.title, iconCls: 'icon-information',
					tooltip: { text: this.dynamicModules.info.title, align: 'bl-tl' },
					overflowText: this.dynamicModules.info.title,
					iconCls: this.dynamicModules.info.icon,
					scope: this,
					handler : function(obj, e) {
						e.stopEvent();
						this.getLoadedModule(this.dynamicModules.info.id, true, function(module) {
								module.createWindow();
						});
					}
				},
				{
					name: 'Logout', iconCls : 'logout',
					tooltip: { text: 'Logout', align: 'bl-tl' },
					overflowText: 'Logout',
					scope : this,
					handler : this.onLogout
				}, '-',
				{ xtype: 'trayclock', flex: 1 }
			]
		});
	},

	onLogout: function (obj,e) {
		e.stopEvent();
		if (isGuest) {
				this.guestLogout();
			}
		else {
			this.saveSessionState();
		}
	},

	onGetUserInfo : function (result, e){
		var t = e.getTransaction();
		if (e.status)
		{
			if (result && result.success)
			{
				// SUCCESS
				var msg = '<b>Login :</b> '+result['login']+'<br/>';
				msg += ('<b> Name :</b> '+result['first_name']+' '+result['name']+'<br/>');
				msg += ('<b>Groups :</b> '+result['group']+'<br/>');
				msg += ('<b>Email :</b> '+result['email']+'<br/>');
				msg += ('<b>Registration date :</b> '+result['date']+'<br/>');
				msg += ('<b>Disk space total / used / available :</b> '+result['total']+' / '+result['used']+' / '+result['available']+' MB<br/>');
				this.infoMsg(msg);
			}
			else
			{
				//ERROR
				this.errorMsg('Cannot get user info');
			}
		}
		else
		{
			// FAILURE
			this.errorMsg('Cannot get user info : '+e.message);
		}
	},

	guestLogout: function() {
		Ext.Msg.show({
			title : 'Logout',
			msg   :'Your guest workspace is to be deleted. Continue logout ?',
			buttons : Ext.Msg.YESNO,
			iconCls : 'logout',
			fn : function(btn) {
				if (btn == 'yes'){
					AmdaAction.logout(true, function(){
						sessionID = '';
						window.location.href ='index.html';
					});
				}
			}
		});
	},

	forceLogout: function(){
		//  myDesktopApp.warningMsg('Your guest session is finished');
		AmdaAction.logout(true, function(){
			sessionID = '';
			window.location.href ='index.html';
		});
	},

	saveSessionState : function()
	{
		var me = this;
		Ext.Msg.show({
			title : 'Logout',
			msg   :'Do you want to keep current windows sizes and locations<br/> for the next sessions?',
			buttons : Ext.Msg.YESNOCANCEL,
			iconCls : 'logout',
			fn : function(btn) {
				if (btn == 'yes'){
					//set wallpaper
					Ext.state.Manager.getProvider().set(me.desktop.id+'_wallpaper',me.desktop.getWallpaper());
					Ext.state.Manager.getProvider().on({
						scope : this,
						aftersave : function(provider) {
							sessionID = '';
							window.location.href ='index.html';
						}
					});
					Ext.state.Manager.getProvider().saveState();
					AmdaAction.logout(false);
				}
				else if (btn == 'no')
				{
					Ext.state.Manager.getProvider().on({
						scope : this,
						aftersave : function(provider) {
							sessionID = '';
							window.location.href ='index.html';
						}
					});
					Ext.state.Manager.getProvider().set(me.desktop.id+'_wallpaper',me.desktop.getWallpaper());
					Ext.state.Manager.getProvider().saveLastTime();
					AmdaAction.logout(false);
				}
			}
		});
	},

	onSettings: function () {
		var dlg = new MyDesktop.Settings({
			desktop: this.desktop
		});
		dlg.show();
	},

	/**
	* initialization at the start of AMDA-NG webApplication
	*/
	initProject : function() 
	{
		moduleIds = new Ext.util.MixedCollection();
		// Adding Workspace Explorer Id
		moduleIds.add(this.dynamicModules.explorer.id);

		moduleIds.each(function(item) {
			this.getLoadedModule(item, true, function (module) {
				module.createWindow();
			});
		}, this);

		if (freeSpace < diskQuota / 20) {
			myDesktopApp.warningMsg('Think of cleaning up your work space.<br/>Only ' +
			Math.round(freeSpace/1024/1024)+ 'MB of '+Math.round(diskQuota/1024/1024) +
			'MB rests');
		}

		if (isFirstVisit && !isGuest) {
            myDesktopApp.getLoadedModule(myDesktopApp.dynamicModules.help.id, true, function(module) {
                module.createWindow();
            });
		}
		else {
			if (isSpecialInfo && !isNewInfo) {
				myDesktopApp.getLoadedModule(myDesktopApp.dynamicModules.info.id, true, function(module) {
					module.createWindow(isSpecialInfo, 'Welcome on AMDA', true);
				});
			}
		}

		if (isNewInfo) {
			myDesktopApp.getLoadedModule(myDesktopApp.dynamicModules.info.id, true, function(module) {
				//  module.createWindow('releaseNotes.' + AMDAVERSION, 'New Release V'+ AMDAVERSION);
				module.createWindow(news, 'Amda Latest News');
			});
		}

		if (isGuest) {
			myDesktopApp.warningMsg("Welcome to Guest Session<br/>Guest session lasts for "+
				guestSessionDuration/3600+" h maximum<br/>"+
				"For extended use time and functionalities (saved sessions)<br/> please register at amda@irap.omp.eu");
			Ext.Function.defer(myDesktopApp.warningMsg,(guestSessionDuration-300)*1000, this, ["Your session will be closed in 5 min!"]);
			Ext.Function.defer(myDesktopApp.forceLogout, guestSessionDuration*1000);
		}

		this.desktop.taskbar.tray.width = 130;
		this.desktop.taskbar.insert(4,new amdaUI.SampToolBarUI({id : 'samptb', onSwitchConnect : function () {
			myDesktopApp.getLoadedModule(myDesktopApp.dynamicModules.interop.id, true, function(module) {
				module.switchSampConnect();
			});
		}}));
	}
});