Ext.define('App.view.FileWindow', {
	extend: 'Ext.window.Window',
	alias: 'widget.fileWindow',

	//title: 'Upload / Download Files',
	scrollable: true,
	constrainHeader: true,
	modal: true,
	width: 800,
	height: 500,

	config: {
		readOnly: false,
	},

	loadGridStore: function(refType, refId) {
		this.down('gridpanel').loadStore(refType, refId);
	},

	loadGridStoreByDoc: function(documentRefType, documentRefId) {
		this.down('gridpanel').loadStoreByDoc(documentRefType, documentRefId);
	},

	getFileIdSkeys: function(){
		var idSkeys = new Array();
		this.down('filegrid').getStore().each(function(record){
			idSkeys[record.getId()]=record.get('skey');
		});
		return idSkeys;
	},

	initComponent: function() {
		var me = this;

		Ext.apply(me, {
			items: [
				{
					xtype: 'fileuploadform',
					params: me.params,
					disabled: me.readOnly,
					margin: '0 0 15 0',
					hidden: me.params.documentRefType || me.readOnly,
				},
				{
					xtype: 'filegrid',
					readOnly: me.readOnly,
				}
			],
			listeners: {
				close: function(window, eOpts) {
					if (me.callbackOnClose) {
						me.callbackOnClose(me.getFileIdSkeys());
					}
				},
			},
		});
		if(me.readOnly){
			me.setTitle('Download Files');
		}else {
			me.setTitle('Upload / Download Files');
		}
		me.callParent(arguments);

		if (me.params.documentRefType && me.params.documentRefId) {
			me.loadGridStoreByDoc(me.params.documentRefType, me.params.documentRefId);
		} else {
			me.loadGridStore(me.params.refType, me.params.refId);
		}
	}

});

// File Upload Form (Single File Upload)
Ext.define('App.view.FileForm', {
	extend: 'Ext.form.Panel',
	alias: 'widget.fileuploadform',

	url: App.url('/file/ul') + '?_csrf=' + App.csrf,
	bodyPadding: 10,
	buttonAlign: 'left',

	onSuccess: function(refType, refId) {
		this.up('window').loadGridStore(refType, refId);
	},

	initComponent: function() {
		var me = this;

		Ext.apply(me, {
			items: [
				{
					xtype: 'hiddenfield',
					name: 'refType',
					value: me.params.refType
				},
				{
					xtype: 'hiddenfield',
					name: 'refId',
					value: me.params.refId
				},
				{
					xtype: 'filefield',
					fieldLabel: 'File',
					name: 'multipartFile',
					allowBlank: false,
					width: 350
				},
				{
					xtype: 'textarea',
					fieldLabel: 'Remarks',
					name: 'description',
					maxLength: 255,
					width: 500
				}
			],
			buttons: [
				{
					text: 'Upload',
					iconCls: 'icon-upload',
					formBind: true,
					handler: function(button, event) {
						var f = me.getForm();
						if (f.isValid()) {
							f.submit({
								waitMsg: 'Saving',
								// url: App.url('/file/ul'),

								success: function(form, action) {
									App.showMsg('Uploaded');
									me.onSuccess(me.params.refType, me.params.refId);
								},
								failure: function(form, action) {
									alert('Upload failure');
								}
							});
						}
					}
				},
				'->',
				{
					text: 'Close',
					margin: '0 0 0 10',
					handler: function(button, event) {
						me.up('window').close();
					}
				}
			]
		});

		me.callParent(arguments);
	}

});

// File Grid
Ext.define('App.view.FileGrid', {
	extend: 'Ext.grid.Panel',
	alias: 'widget.filegrid',

	titleName: 'File List',
	//columnLines: true,
	minHeight: 195,
	//maxHeight: 320,
	style: {
		"border-radius": "0px"
	},
	config: {
		readOnly: false,
		extraOpenFileFunc: null,
	},
	refType: null,
	refId: null,
	getRef: function(){
		return { refType: this.refType, refId: this.refId };
	},
	reload: function(){
		this.getStore().reload();
	},

	loadStore: function(refType, refId, startDate, endDate) {
		var me = this;
		me.refType = refType;
		me.refId = refId;
		me.getStore().load({
			method: 'POST',
			params: { refType: refType, refId: refId, startDate: startDate, endDate: endDate },
			callback: function(records, operation, success) {
				if(me.titleName) me.setTitle(me.titleName + ' (' + me.getStore().getCount()+')');

				// numberer
				var numberer = 1;
				me.getStore().each(function(record){
					record.set('numberer',numberer++);
					record.commit();
				});
			},
			scope: me
		});
	},	

	loadStoreByDoc: function(documentRefType, documentRefId) {
		var me = this;
		me.documentRefType = documentRefType;
		me.documentRefId = documentRefId;
		me.getStore().load({
			method: 'POST',
			params: { documentRefType: documentRefType, documentRefId: documentRefId },
			callback: function(records, operation, success) {
				if(me.titleName) me.setTitle(me.titleName + ' (' + me.getStore().getCount()+')');

				// numberer
				var numberer = 1;
				me.getStore().each(function(record){
					record.set('numberer',numberer++);
					record.commit();
				});

				me.down('#removeActionCol').setHidden(true);
			},
			scope: me
		});
	},

	reloadStore: function(){
		this.getStore().reload();
	},
	// onRecordChange: function(record) {
	// 	Ext.Msg.confirm('Change', 'Confirm?', function(btn) {
	// 		if (btn == 'yes') {
	// 			Ext.Ajax.request({
	// 				url: App.url('/file/update'),
	// 				params: {
	// 					id: record.getId(),
	// 					skey: record.get('skey'),
	// 					filename: record.get('filename'),
	// 					description: record.get('description')
	// 				},
	// 				success: function(response, opts) {
	// 					var o = Ext.decode(response.responseText);
	// 					if (o.success) {
	// 						record.commit();
	// 						App.showMsg('Filename updated');
	// 					} else {
	// 						record.reject();
	// 						App.showError('Action failed!');
	// 					}
	// 				}
	// 			});
	// 		} else {
	// 			record.reject();
	// 		}
	// 	});
	// },

	initComponent: function() {
		var me = this;
		Ext.apply(me,{
			title: me.titleName,
		});
		Ext.applyIf(me, {
			store: Ext.create('App.store.FileStore', {}),

			// plugins: {
			// 	ptype: 'cellediting',
			// 	clicksToEdit: 1,
			// 	listeners: {
			// 		beforeedit: function(editor, context){
			// 			return !me.readOnly;
			// 		},
			// 		edit: function(editor, e) {
			// 			if (!me.readOnly && e.value != e.originalValue) me.onRecordChange(e.record);
			// 		}
			// 	}
			// },

			columns: [
				{
					text: '#',
					align: 'center',
					width: 32,
					dataIndex: 'numberer',
				},
				{
					xtype: 'actioncolumn',
					menuDisabled: true,
					align: 'center',
					width: 32,
					items: [
						{
							iconCls: 'icon-download',
							tooltip: 'Download the file',
							handler: function(grid, rowIndex, colIndex, item, e, record, row) {
								var url = Ext.String.format(App.url('/file/dl/') + '{0}/{1}/{2}?dl=1', record.getId(), record.get('skey'), record.get('filename'));
								window.open(url);
								if(me.extraOpenFileFunc) me.extraOpenFileFunc(record.getId());
							}
						}
					]
				},
				{
					dataIndex: 'filename',
					menuDisabled: true,
					text: 'File Name',
					flex: 1,
					renderer: function(value, metaData, record, row, col, store, gridView){
						var qtip = Ext.String.format('View <b>{0}</b> if supported by your browser and/or software, else download the file', value);
						if (metaData) metaData.tdAttr = 'data-qtip="' + qtip + '"';

						var extId = Ext.id();
						setTimeout(function() {
							if (Ext.fly(extId)) {
								Ext.EventManager.addListener(
									extId, 'click',
									function() {
										var url = Ext.String.format(App.url('/file/dl/') + '{0}/{1}/{2}', record.getId(), record.get('skey'), value);
										window.open(url);
										if(me.extraOpenFileFunc) me.extraOpenFileFunc(record.getId());
									}
								);
							}
						}, 200);
						return Ext.String.format('<a href="javascript:void(0);" id="{0}">{1}</a>', extId, value);
					},
					// editor: {
					// 	xtype: 'textfield',
					// 	validator: function(v) {
					// 		return v.match(/^(?!\.)(?!com[0-9]$)(?!con$)(?!lpt[0-9]$)(?!nul$)(?!prn$)[^\|\*\?\\:<>/$"]*[^\.\|\*\?\\:<>/$"]+$/) ? true : 'Invalid filename!';
					// 	}
					// }
				},
				{
					dataIndex: 'filesize',
					menuDisabled: true,
					text: 'File Size',
					align: 'right',
					width: 95,
					renderer: function(value, metaData, record, row, col, store, gridView){
						return Ext.util.Format.fileSize(value);
					}
				},
				{
					dataIndex: 'created',
					menuDisabled: true,
					text: 'Uploaded Date',
					width: 120,
					renderer: function(value, metaData, record, rowIndex, colIndex, store, grid){
						var text = Ext.util.Format.date(value, App.dateTimeFormat);
						if (metaData) metaData.tdAttr = 'data-qtip="' + text + '"';
						return text;
					}
				},
				{
					dataIndex: 'createdByName',
					menuDisabled: true,
					text: 'Uploaded By',
					width: 120,
					renderer: function(value, metaData, record, rowIndex, colIndex, store, grid){
						if (metaData) metaData.tdAttr = 'data-qtip="' + value + '"';
						return value;
					}
				},
				// {
				// 	dataIndex: 'created',
				// 	menuDisabled: true,
				// 	text: 'Uploaded By',
				// 	width: 120,
				// 	renderer: function(value, metaData, record, rowIndex, colIndex, store, grid){
				// 		var text = Ext.util.Format.date(value, App.dateTimeFormat);
				// 		if (metaData) metaData.tdAttr = 'data-qtip="' + record.get('createdByName') + ' - ' + text + '"';
				// 		return record.get('createdByName') + ' - ' + text;
				// 	}
				// },
				{
					dataIndex: 'description',
					menuDisabled: true,
					text: 'Remarks',
					width: 120,
					renderer: function(value, metaData, record, rowIndex, colIndex, store, grid){
						if (metaData) metaData.tdAttr = 'data-qtip="' + value + '"';
						return value;
					},
					editor: {
						xtype: 'textfield',
						maxLength: 255
					}
				},
				{
					xtype: 'actioncolumn',
					itemId: 'removeActionCol',
					menuDisabled: true,
					hideable: false,
					align: 'center',
					width: 32,
					items: [
						{
							iconCls: 'silk-cross',
							tooltip: 'Delete the file',
							handler: function(grid, rowIndex, colIndex, item, e, record, row) {
								if (!me.readOnly && confirm('Confirm?')) {
									Ext.Ajax.request({
										url: App.url('/file/delete'),
										method: 'POST',
										params: { fileId: record.getId(), skey: record.get('skey'), refType: record.get('refType'), refId: record.get('refId') },
										success: function(response, opts){
											var o = Ext.decode(response.responseText);
											if (o.success) {
												me.getStore().reload();
												App.showMsg('File deleted');
											}
										},
										failure: function(response, opts){
											App.showError('Action failed!');
										}
									});
								}
							}
						}
					]
				}
			]
		});

		// remove delete btn
		if(me.readOnly) me.columns.pop();

		me.callParent(arguments);

		if (me.params) me.loadStore(me.params.refType, me.params.refId);
	}

});
