/**
 * Project   : AMDA-NG
 * Name      : UploadUI.js
 * @class    amdaUI.UploadUI
 * @extends  Ext.form.Panel 
 * @brief    Upload Panel UI definition (View)
 * @author 	 Elena
 * @version  $Id: UploadPanelUI.js 2831 2015-03-26 10:33:42Z elena $            
 */

Ext.define('amdaUI.UploadPanelUI', {
	extend: 'Ext.form.Panel',
	alias: 'widget.panelUpload',
	
	requires : [
		'amdaUI.RemoteSearchPlugin'
	],

	tmpNode : null,
	specialItems : null,
	formats : null,
	localName : null,
	
	constructor: function(config) 
	{  
		this.init(config);
		this.callParent(arguments);
	},

	/*
	* create MyData linked node and edit in module MyData
	* update myDataParams info if needed
	*/
	getObjectCallback : function(result,remoteEvent)
	{                    
		var t = remoteEvent.getTransaction();
		if (result && !result.error) 
		{
			// set parameter into node
			var me = this;
			myDesktopApp.getLoadedModule(this.tmpNode.get('moduleId'), true, function (module){
				// myData
				if (me.tmpNode.get('nodeType') == amdaModel.MyDataParamNode.nodeType) {		       
					var linkedFile = Ext.create('amdaModel.MyDataNode', {leaf : true, text : me.tmpNode.get('text')});
							
					linkedFile.create(result.mask, result.description, result.maskDesc);
					linkedFile.updateMyDataParam(result.mask,result.maskDesc); 
					
					if (!linkedFile.get('id')) 
						linkedFile.set('id',me.tmpNode.get('text'));   
		
					var paramObj = Ext.create(linkedFile.get('objectDataModel'), result);
					linkedFile.set('object',paramObj);
					me.tmpNode.set('fileObject',paramObj);
				}
				else {
					// Time Table or Catalog
					var paramObj = Ext.create(me.tmpNode.get('objectDataModel'), result);
					
					paramObj.set('fromPlugin',true);
					if (result.intervals) {
						paramObj.set('intervals',result.intervals);
						paramObj.set('nbIntervals',result.intervals.length);
					}
					me.tmpNode.set('object',paramObj);
				}	
				if (module) {
					module.setLinkedNode(me.tmpNode); 	      
					module.linkedNode.editInModule();  
				}
			}); 
		} 
		else {   
			// EXCEPTION : parameter not found !
			myDesktopApp.errorMsg(t.action + "." + t.method + " : No parameter '"+this.tmpNode.get('text')+"' found!");	     
		}
		
		loadMask.hide();
	},
        
/*
*  form validation
*/
	validate : function() 
	{
		var values = this.getForm().getValues();

		if (values['filesrc'] == 'LOCAL') 
		{
			var locFile = this.getForm().findField(this.localName).getValue();

			if (!locFile) {
				myDesktopApp.warningMsg("Select File to Upload");
				return false;
			}
		}
		else 
		{
			if (!values['remoteFile'] && !values['remoteTT'] && !values['remoteCat']) {
				myDesktopApp.warningMsg("Select File to Upload");
				return false;
			}
		}
		
		return true;
	},

        
/*
 *  Upadte format if user didn't do this himself
 */
	updateFormat: function(value) 
	{    
		var arrayOfStr = value.split('.');

		var radios = Ext.getCmp(this.radioId);
		var user_format_obj = radios.getValue();

		var user_format = user_format_obj[this.radioId];
		
		//  auto define format in some special cases 
		//TODO name without extention => ASCII?
		if (arrayOfStr.length == 1) {
			auto_format = 'ASCII'; 
		}
		else  {
			var suffix = arrayOfStr[arrayOfStr.length - 1].toLowerCase();
			if (suffix == 'gz') 
				suffix = arrayOfStr[arrayOfStr.length - 2].toLowerCase() + '.gz';

			switch (suffix)
			{
				case 'cdf' :  auto_format = 'CDF'; break;
				case 'cef.gz' :
				case 'cef' :  auto_format = 'CEF'; break;
				case 'xml' :  auto_format = 'VOT';
				case 'vot' :  auto_format = 'VOT'; break;
				case 'nc'  :  auto_format = 'NC';  break;
				case 'asc' :
				case 'txt' :			 
				default : auto_format = 'ASCII'; 			   
			}
		} 
		// set auto format : case when format was not set by user before   
		if (user_format !== auto_format) {
			user_format_obj[this.radioId] = auto_format;    
		} 

		radios.setValue(user_format_obj);
	},
 
/*
* 
*/
	forceUpload : function (url,format,onFinish)
	{
		var me = this;
		var re = /http:\/\/127.0.0.1:/;
		var isRemoteUrl = !re.test(url);

		switch (format) {
			case 'votable' :
				this.getForm().findField('filefrmt').setValue('VOT');
				break;
			case 'cdf' :
				this.getForm().findField('filefrmt').setValue('CDF');
				break;
			default :
				myDesktopApp.errorMsg('Not supported data receive from SAMP');
				return;
		}

		if (!isRemoteUrl) {
			myDesktopApp.getLoadedModule(myDesktopApp.dynamicModules.interop.id, true, function (module) {
				var onError = function(error) {
					if (error)
						myDesktopApp.errorMsg(error);
					else
						myDesktopApp.errorMsg("Cannot load data from this SAMP notification");
					if (onFinish)
						onFinish();
				};
				var onLoad = function(data) {
					//Fake value for validation
					Ext.form.field.File.superclass.setValue.call(me.getForm().findField('localFileName'), 'samp.vot');
					me.getForm().findField('filesrc').setValue('LOCAL');
					//Add data related to the samp notification
					me.getForm().findField('sampFileName').setValue('samp.vot');
					me.getForm().findField('sampData').setValue(data);
					var onFinishAll = function() {
						me.getForm().findField('sampFileName').reset();
						me.getForm().findField('sampData').reset();
						if (onFinish)
							onFinish();
					}
					me.postUpload(onFinishAll);
				};
				module.loadFile(url,onLoad,onError);
			});
			return;
		}
		
		this.getForm().findField('filesrc').setValue('URL');
		this.getForm().findField('remoteFile').setValue(url);
		this.postUpload(onFinish);
	},
        
/*
* 
*/
	postUpload : function(onFinish)
	{
		// 'global' form containing 'partial' forms				      
		var form = this.getForm();

		// special validation 	            
		if(this.validate())
		{
			loadMask.show();					
			form.submit({
				scope: this,
				url: 'php/uploadFile.php',
				waitMsg: 'Uploading your file...',
				success: function(form, o) {
					if (onFinish)
						onFinish();
					this.tmpNode = Ext.create(this.nodeType,{leaf : true, text : o.result.file});
					AmdaAction.getUploadedObject(o.result.file, o.result.format, this.tmpNode.get('nodeType'), this.getObjectCallback, this);
					loadMask.hide();
				},
				failure: function(form, o) {
					if (onFinish)
						onFinish();
					loadMask.hide();
					myDesktopApp.errorMsg('Error '+o.result.error); 
				}
			});
		}		
	},
	
	initFileUpload : function()
	{
		this.formats = [
				{ boxLabel: 'ASCII', name: 'filefrmt', inputValue: 'ASCII', checked: true,
					listeners: {
						change: function (cb, nv, ov) {
							if (nv) { 
								Ext.getCmp('tf').show();
							}
							else {
								Ext.getCmp('tf').hide();
								Ext.getCmp('nfs').hide();
							}
						}
					} 
				}, 
				{ boxLabel: 'netCDF&nbsp;<img amda_clicktip="ncTimeFormat" style="vertical-align:bottom" src="js/resources/images/16x16/info_mini.png"', name: 'filefrmt', inputValue: 'NC' },
				{ boxLabel: 'CDF&nbsp;<img amda_clicktip="cdfTimeFormat" style="vertical-align:bottom" src="js/resources/images/16x16/info_mini.png"', name: 'filefrmt', inputValue: 'CDF' },
			// { boxLabel: 'CEF[GZ]', name: 'filefrmt', inputValue: 'CEF' },
				{ boxLabel: 'VOTable', name: 'filefrmt', inputValue: 'VOT' }];

			this.localUploadId = 'form-uploadfile';
			this.remoteUploadId = 'form-uploadurl'; 	 
			this.nodeType = 'amdaModel.MyDataParamNode';	   
			this.store = Ext.create('Ext.data.Store', {
				fields: ['value', 'name'],
				proxy: {
					type: 'ajax',
					url : 'generic_data/remote_sites.json',
					reader: {
						type: 'json',
						root: 'remote_sites'
					}
				},
				autoLoad: true
			});
			
			this.radioId = 'filefrmt';

/*
 *  Sampling : TimeFormat Fieldset  
 */    
		this.autoSampling = Ext.create('Ext.form.RadioGroup', {
		//	fieldLabel : 'Constant or Variable ?',
		//	labelWidth: 90,
			defaults : {name : 'timesmpl'},
			items: [
				{boxLabel: 'constant sampling', inputValue: 'constant', checked: true},
				{boxLabel: 'variable sampling&nbsp;<img amda_clicktip="variableSampling" style="vertical-align:bottom" src="js/resources/images/16x16/info_mini.png"', inputValue: 'variable'}	  
			]
		});
		
		this.manualSampling = Ext.create('Ext.form.FieldContainer', { 
			defaultType: 'numberfield',
			layout: 'anchor',
			defaults: {
				layout: '100%',
				labelWidth : 150,
				minValue : 0.001,
				hideTrigger: true
			}, 
			hidden : true,
			items: [  
			{ 
				fieldLabel : 'min sampling',	
				name : 'min_manual_sampling'
			},  
			{ 
				fieldLabel : 'max sampling',	
				name : 'max_manual_sampling'				   
			}]
		}); 
	
		var Sampling = Ext.create('Ext.form.RadioGroup', {
			fieldLabel: 'Time Sampling',
			labelWidth: 90,   
			cls: 'x-check-group-alt',	
			defaults : {name : 'smpl'},
			items: [
				{boxLabel: 'auto-defined', inputValue: 'auto', checked: true},
				{boxLabel: 'manual', inputValue: 'manual'}
			],
			listeners: {
				scope : this,
				change: function (cb, nv, ov) {
					if (nv.smpl == 'manual') {
							this.autoSampling.setVisible(false);
							this.manualSampling.setVisible(true);
					}
					else {   
							this.autoSampling.setVisible(true);
							this.manualSampling.setVisible(false);
					}
				}
			}
		});
		
/*
 *  NonStandardFormat : TimeFormat Fieldset  
 */
		var nonStandardFormat = { 
			xtype: 'fieldcontainer',
			defaultType: 'textfield',
			layout: 'anchor',
			defaults: {
				layout: '100%',
				labelWidth : 150 
			}, 
			id : 'nfs', 
			hidden : true,
			items: [  
			{ 
				fieldLabel : 'define time format',	
				name : 'nonstd',				   
				value: 'Y-m-d H:i:s',
				enableKeyEvents: true,
				listeners : {
					keyUp : function() {
						if (this.getValue().indexOf('z') > 0) {
							this.nextSibling().show();
						}                                                 
						if (this.getValue().indexOf('d') > 0) {
							this.nextSibling().hide();
						}                                                 
					}
				}
			},{ 
				xtype: 'checkbox',  
				name : 'doy',
				fieldLabel: 'DOY starts from 1',
				hidden : true,
				inputValue: '1'
			},{ 
				fieldLabel : 'define max time length',
				name : 'timelength',
				value: 'auto'    
			}],
			listeners : {
				hide : function() {
						this.items.getAt(1).hide();                                                
				},
				show : function() {
					if (this.items.getAt(0).getValue().indexOf('z') > 0)
						this.items.getAt(1).show();                                                
				}
			}
		};
		
/*
 *  TimeFormat Fieldset :  Global form
 */
		var timeFormat = Ext.create('Ext.form.FieldSet', {
			title: 'Time Settings',
			items : [{
				id: 'tf',
				xtype: 'radiogroup',
				fieldLabel: 'Time Format',
				labelWidth: 90,   
				cls: 'x-check-group-alt',
				defaults : { name : 'timefrmt'},
				items: [ 
					{ boxLabel: 'standard&nbsp;<img amda_clicktip="standardTimeFormat" style="vertical-align:bottom" src="js/resources/images/16x16/info_mini.png"', inputValue: 'standard', checked: true},     			
					{ boxLabel: 'no&nbsp;<img amda_clicktip="userTimeFormat" style="vertical-align:bottom" src="js/resources/images/16x16/info_mini.png"', inputValue: 'user', 
						listeners: {
							change: function (cb, nv, ov) {
								if (nv) 
										Ext.getCmp('nfs').show();
								else    
										Ext.getCmp('nfs').hide();	
							}
						}      
					}]
				},
				nonStandardFormat,
				Sampling,
				this.autoSampling,
				this.manualSampling
			]
		});
		
		this.specialItems = [ timeFormat,
					{
						xtype: 'hidden',
						name: 'sampData',
						value: null
					},
					{
						xtype: 'hidden',
						name: 'sampFileName',
						value: null
					}]
	},
	
	initTTUpload : function(isTT)
	{
		if (isTT) {
			this.formats = [
				{ boxLabel: 'ASCII&nbsp;<img amda_clicktip="ttTimeFormat" style="vertical-align:bottom" src="js/resources/images/16x16/info_mini.png"', name: 'ttfrmt',  inputValue: 'ASCII', checked: true},
				{ boxLabel: 'VOTable', name: 'ttfrmt', inputValue: 'VOT'}
			];
			this.localUploadId = 'form-uploadtt';
			this.remoteUploadId = 'form-uploadtturl'; 
			this.nodeType = 'amdaModel.TimeTableNode';
		    
			this.store = Ext.create('Ext.data.Store', {
				fields: ['value', 'name']/*,
				proxy: {
					type: 'ajax',
					url : 'generic_data/remote_sites.json',
					reader: {
						type: 'json',
						root: 'remote_sites'
					}
				},
				autoLoad: true*/
			});
			
			this.radioId =	'ttfrmt';
		}
		else {
			this.formats = [
				{ boxLabel: 'VOTable', name: 'catfrmt', inputValue: 'VOT', checked: true }];
						
			this.localUploadId = 'form-uploadcat';
			this.remoteUploadId = 'form-uploadcaturl'; 
			this.nodeType = 'amdaModel.CatalogNode';
			this.store = Ext.create('Ext.data.Store', {
				fields: ['value', 'name']/*,
				proxy: {
					type: 'ajax',
					url : 'generic_data/remote_sites.json',
					reader: {
						type: 'json',
						root: 'remote_sites'
					}
				},
				autoLoad: true*/
			}); 
			
			this.radioId = 'catfrmt';
		}
	},
/*
*  panel config
*/
	init : function(config) 
	{       
		 
		if ( config.panelType == 'file' )
				this.initFileUpload();
		else 
				this.initTTUpload(config.panelType == 'timetable');

		this.localName = config.localUploadName;
 /*
 *  FileFormat Fieldset 
 */ 
		var fileFormat =  Ext.create('Ext.form.FieldSet', { 			      
			title: 'File Format',			     		     
			items : [{ 
				xtype: 'radiogroup',
				id : this.radioId, 
				columns: 3,
				cls: 'x-check-group-alt',
				items: this.formats
			}]
		}); 

/*
 * FileSource Fieldset : Local File Upload
 */
		var localFile = Ext.create('Ext.form.Panel', {      
			id: this.localUploadId,
			fileUpload: true,
			hideLabels: true,
			frame: true,			      
			items: [{
				xtype: 'fileuploadfield',     
				emptyText: 'Select Your File',
				width: 300,
				name: this.localName,  
				buttonText: 'Browse',
				listeners: {
					scope : this,
					change: function (field, value, e) {
							this.updateFormat(value);	
					} 
				}
			},
			{  
				// it is common setting for Local and Remote files
				xtype : 'hiddenfield',
				name: 'MAX_FILE_SIZE',
				value: myDesktopApp.MAX_UPLOADED_FILE_SIZE // 30MB	 			      
			}] 
		});
		
/*
 * FileSource Fieldset : Remote File Upload
 */
		var combo = Ext.create('Ext.form.ComboBox', {
				flex : 4, 
				store: this.store,
				emptyText: 'Enter Remote Site URL (ftp/http)',
				queryMode: 'local',
				displayField: 'name',
				valueField: 'value' 
		});
	    	  
		var fieldcontainer = { 
			xtype: 'fieldcontainer', 
			fieldLabel: ' ', labelWidth: 0, labelSeparator : '', labelPad : 0,
			layout: 'hbox',		
			items: [
				combo,
				{
					xtype : 'button',
					flex : 1,
					text: 'Browse It',								   
					handler: function() {					      
						var form = this.up('form').getForm(); 
						var site = form.getFields().getAt(0).getValue(); 					    
						if (site) 						   
							this.up('form').ownerCt.fireEvent('open', site);
						else 
							myDesktopApp.warningMsg("Please Enter Remote Site URL");				 
					} 
				}]
		};
		
		var remoteFile = Ext.create('Ext.form.Panel', { 
			id: this.remoteUploadId, 
			hideLabels: true,
			autoHeight: true, 
			frame: true,
			hidden : true,
			items: [  
				fieldcontainer,
				{ 
					xtype : 'textfield',
					name : config.remoteUploadName, 
					emptyText: 'Enter Remote File URL (ftp/http)',
					width: 310,
					listeners: 
					{
						scope : this,
						change: function (field, value, e) {
									this.updateFormat(value);
						} 
					}
				}]
		});
		
 /*
 * FileSource Fieldset  :  global form
 */                                       
		var uploadForm = Ext.create('Ext.form.FieldSet',{    
			title: 'File Source',     
			items : [{ 
				xtype: 'radiogroup', 
				cls: 'x-check-group-alt',
				items: [
					{ boxLabel: 'Local', name: 'filesrc', inputValue: 'LOCAL', checked: true,
						listeners: {
							scope : this,
							change: function (cb, nv, ov) {
								if (nv == ov) return;
								var local = Ext.getCmp(this.localUploadId);
								var remote = Ext.getCmp(this.remoteUploadId);
								if (nv) {
										remote.hide();
										local.show();
								}
								else  {
										local.hide();
										remote.show();    
								}   
							}
						} 
					},
					{ boxLabel: 'URL', name: 'filesrc', inputValue: 'URL'}]
			}]
		});		      

/*
 * Panel Config
 */
		var myConf = 
		{
			title : config.title,  
			layout: {type: 'vbox', align: 'stretch'},
			autoScroll : true,
			bodyStyle: { background : '#dfe8f6'},
			items : Ext.Array.merge(
					[ uploadForm, localFile, remoteFile, fileFormat ],
					this.specialItems ), 
			buttons: [{
				text: 'Upload',
				handler: function() {
					this.postUpload();
				},
				scope : this
			},
			{
				text: 'Reset',
				handler: function() {      
					this.up('form').getForm().reset();  
				}
			}], 
			plugins: [{ptype: 'remoteSearchPlugin'}],
			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);
							}); 
						}
					}
				}
			}
		};

		Ext.apply (this, Ext.apply(arguments, myConf));	 	  
	}		 
});