Ext.define('Ext.ux.folderExplorer.Grid', {
	extend: 'Ext.grid.Panel',
	alias: 'widget.folderExplorerGrid',
	initComponent: function() {
		var me = this;

		me.setupI18N();

		var modelName = 'folderExplorerRows';

		var url = '/ip2-services/ip2services.aspx?func=getFolderExplorerRows';

		if (me.path) {
			url += '&path=' + me.path;
		}
		if (me.extentions) {
			url += '&extnList=' + me.extentions;
		}

		if (!Ext.ClassManager.isCreated(modelName)) {
			Ext.define(modelName, {
				extend: 'Ext.data.Model',
				proxy: {
					type: 'ajax',
					url: url,
					reader: {
						type: 'json',
						rootProperty: 'rows'
					}
				}
			});
		}

		me.columns = me.columns || [];
		me.columns.push(
			{ header: me.getI18N('name'), dataIndex: 'name', flex: 1 }
		);
		me.columns.push(
			{ header: me.getI18N('importDate'), dataIndex: 'ts', width: 100, renderer: me.ts2dateRenderer }
		);
		me.columns.push(
			{ header: me.getI18N('importTime'), dataIndex: 'ts', width: 100, renderer: me.ts2timeRenderer }
		);
		me.columns.push(
			{
				xtype: 'actioncolumn',
				width: 25,
				items: [{
					iconCls: 'pf-eye',
					text: me.getI18N('showLog'),
					tooltip: me.getI18N('showLogTips').toString(),
					handler: function(view, rowIndex, colIndex) {
						var grid = view.up('grid');
						var record = grid.getStore().getAt(rowIndex);

						var win = Ext.create('Ext.ux.folderExplorer.LogWindow', {
							record: record
						});
						win.show();
					},
					getClass: function(value, meta, record) {
						if (record.get('logs') == 0) {
							return '';
						}
						else {
							return 'pf-eye';
						}
					}
				}]
			}
		);
		me.columns.push(
			{ header: me.getI18N('noOfLogs'), dataIndex: 'logs', width: 100, renderer: me.noOfLogsRenderer }
		);

		me.store = Ext.create('Ext.data.Store', {
			model: modelName,
			autoLoad: true
		});

		me.dockedItems = [{
			xtype: 'toolbar',
			dock: 'top',
			items: [{
				xtype: 'button',
				text: me.getI18N('refresh'),
				iconCls: 'pf-refresh',
				handler: function() {
					me.store.load();
				}
			},{
				xtype: 'button',
				text: me.getI18N('upload'),
				iconCls: 'pf-arrow-up',
				handler: function() {
					me.upload();
				}
			}]
		}];

		me.callParent();
	},

	/* ---------------------------------------------------------------------------------------------------
	Renderer timestamp to date
   ---------------------------------------------------------------------------------------------------- */
	ts2dateRenderer: function(value) {
		if (value == 0) {
			return '';
		}

		var year = Ext.Date.format(value, 'Y');

		if (year == 1970) {
			return '';
		}

		return Ext.Date.format(value, 'd.m.Y');
	},

	/* ---------------------------------------------------------------------------------------------------
	Renderer timestamp to time
   ---------------------------------------------------------------------------------------------------- */
	ts2timeRenderer: function(value) {
		if (value == 0) {
			return '';
		}

		var year = Ext.Date.format(value, 'Y');

		if (year == 1970) {
			return '';
		}

		return Ext.Date.format(value, 'H.i.s');
	},

	/* ---------------------------------------------------------------------------------------------------
	Renderer number of logs
   ---------------------------------------------------------------------------------------------------- */
	noOfLogsRenderer: function(value) {
		if (value == 0) {
			return '';
		}

		return value;
	},

	/* ---------------------------------------------------------------------------------------------------
	Upload
   ---------------------------------------------------------------------------------------------------- */
	upload: function(value) {
		var me = this;

		Ext.create('Ext.window.Window', {
			title: me.getI18N('upload'),
			bodyStyle: {
				padding: '10px',
				'background-color': 'white'
			},
			items: [{
				xtype: 'form',
				border: false,
				items: [{
					xtype: 'fileuploadfield',
					name: '*ILOB:uploadIlob',
					emptyText: me.getI18N('browse_placeholder'),
					buttonText: me.getI18N('browse'),
					width: 500
				}]
			}],
			buttons: [{
				xtype: 'button',
				text: me.getI18N('upload'),
				iconCls: 'pf-arrow-up',
				handler: function() {
					var win = this.up('window');
					var form = win.down('form');
					var field = form.down('fileuploadfield');
					var file = field.getValue();
					if (Ext.isEmpty(file)) {
						Ext.Msg.show({
							title: me.getI18N('message'),
							msg: me.getI18N('select_a_spreadsheet'),
							buttons: Ext.Msg.OK,
							icon: Ext.Msg.ERROR
						});
						return;
					}
					if (file.indexOf('.xls') == -1) {
						Ext.Msg.show({
							title: me.getI18N('message'),
							msg: me.getI18N('must_be_a_spreadsheet'),
							buttons: Ext.Msg.OK,
							icon: Ext.Msg.ERROR
						});
						return;
					}

					me.setLoading(
						ip2.i18n({
							da: 'Vent venligst...',
							en: 'Please wait...'
						})
					);

					var files = field.fileInputEl.dom.files;
					var fileName = files[0].name;

					var formData = new FormData();
					var xhr = new XMLHttpRequest();

					var filepath = me.path + '/' + fileName;
					formData.append(filepath, files[0]);

					xhr.onreadystatechange = function () {

						if (xhr.readyState == 4 && xhr.status == 200) {
							var result;

							me.setLoading(false);

							try {
								result = Ext.decode(xhr.responseText);
							}
							catch (err) {}

							if (result[0].success) {
								win.close();
							}
						}
					};

					xhr.open('POST', 'ip2-services/webbios.aspx?action=movestmf&ignoreStaticDir=true&path=' + me.path, true);
					xhr.send(formData);
				}
			},{
				xtype: 'button',
				text: me.getI18N('cancel'),
				iconCls: 'pf-navigate_cross',
				handler: function() {
					var win = this.up('window');
					win.close();
				}
			}]
		}).show();
	},

	/* ----------------------------------------------------------------------------------------------------
		Setup I18N
	---------------------------------------------------------------------------------------------------- */
	setupI18N: function() {
		var texts = {
			ns: 'IP2',
			lang: ['da', 'en'],
			enums: {},
			text: {
				refresh: {
					value: { da: 'Opfrisk', en: 'Refresh' }
				},
				upload: {
					value: { da: 'Upload', en: 'Upload' }
				},
				browse: {
					value: { da: 'Gennemse...', en: 'Browse...' }
				},
				browse_placeholder: {
					value: { da: 'Gennemse for at vælge regneark', en: 'Browse for select a spreadsheet' }
				},
				select_a_spreadsheet: {
					value: { da: 'Vælg venligst et regneark', en: 'Please select a spreadsheet' }
				},
				must_be_a_spreadsheet: {
					value: { da: 'Den valgte skal være et regneark', en: 'The selected must be a spreadsheet' }
				},
				cancel: {
					value: { da: 'Luk', en: 'Cancel' }
				},
				name: {
					value: { da: 'Navn', en: 'Name' }
				},
				importDate: {
					value: { da: 'Importet d.', en: 'Date of import' }
				},
				importTime: {
					value: { da: 'Importet kl.', en: 'Time of import' }
				},
				noOfLogs: {
					value: { da: 'Antal logs', en: 'Number of logs' }
				},
				showLog: {
					value: { da: 'Vis logs', en: 'Show logs' }
				},
				showLogTips: {
					value: { da: 'Vis logs', en: 'Show logs' }
				},
				confirmImportTitle: {
					value: { da: 'Bekræft import', en: 'Confirm import' }
				},
				confirmImport: {
					value: { da: 'Bekræft venligst import af: ', en: 'Please confirm import of: ' }
				},
				receipt: {
					value: { da: 'Kvittering', en: 'Receipt' }
				},
				message: {
					value: { da: 'Meddelelse', en: 'Message' }
				},
				logWindowTitle: {
					value: { da: 'Log:', en: 'Log:' }
				},
				please_wait: {
					value: { da: 'Vent venligst...', en: 'Please wait...' }
				}
			}
		};

		ip2.folderExplorer = new ip2.DynamicNS(texts);
		ip2.folderExplorer.setLanguage(ip2.session.getLanguage());
	},

	/* ----------------------------------------------------------------------------------------------------
		get I18N by key
	---------------------------------------------------------------------------------------------------- */
	getI18N: function(key) {
		return ip2.i18n(ip2.folderExplorer.getTextValue(key));
	}
});
