Ext.define('Ext.ux.grid.Browser', {

	extend: 'Ext.grid.Panel',

	alias: 'widget.gridbrowser',

	mixins: {
		keyMapping: 'Ext.ux.util.KeyMapping'
	},

	extensions: '*',
	overwriteColumns: false,
	path: '/',
	service: null,

	pagebar: true,
	pagebarSizeEdit: true,
	pagebarSearch: true,
	pagebarSearchEmptyText: 'Search...',
	pagebarSearchWidth: 200,
	pagebarPosition: 'top',
	pageSize: 20,

	value: null,

	multiSelect: false,

	initComponent: function() {

		var i_cmp = this;
		var o_initial = i_cmp.initialConfig;

		var s_service = o_initial.service || (function () {
			var s_path = o_initial.path || i_cmp.path;
			return '/ip2-services/webbios.aspx?pathList=' + s_path + '&environment=gallery&omitList=system,_lock';
		})();

		var i_store = Ext.create('Ext.data.Store', {
			fields: ['name', 'path'],
			autoLoad: true,
			pageSize: o_initial.pageSize || i_cmp.pageSize,
			proxy: {
				type: 'ajax',
				url: s_service,
				reader: {
					type: 'json',
					root: 'rows',
					totalProperty: 'totalRows'
				},
				extraParams: {
					func: 'listDirByExtension',
					extnList: o_initial.extensions || i_cmp.extensions,
					metaData: true
				}
			}
		});

		// Prepare the default config object to apply
		var o_config = {
			cls: 'x-ux-imagegrid',
			store: i_store,
			listeners: {
				'itemdblclick': {
					fn: function () {
						i_cmp.doItemSelection();
					}
				}
			},
			columns: [
				{
					dataIndex: 'path',
					width: 70,
					renderer: function (s_path) {

						var s_height = 30;
						var b_image;

						b_image = (function (s_path) {

							var s_extension = s_path.split('.').pop().toLowerCase();
							var a_extension = ['gif', 'tiff', 'jpg', 'jpeg', 'tga', 'png', 'targa'];
							var b_image = Ext.Array.indexOf(a_extension, s_extension) > -1;

							return b_image;
						})(s_path);

						if (!b_image) {

							s_path = (function (s_path) {

								var a_file = s_path.split('.');
								var s_extension = a_file.pop();
								var a_extension = ['doc', 'docx', 'xls', 'xlsx', 'pdf', 'ppt'];
								var s_path;

								if (Ext.Array.indexOf(a_extension, s_extension) > -1) {
									s_path = '/portfolio/styles/icon/flatiu//media/' + s_extension + '.png';
								}
								else {
									s_path = '/portfolio/styles/icon/flatiu//media/generic-doc.png';
								}

								return s_path;
							})(s_path);
						}

						return '<img height="' + s_height + '" src="' + s_path + '">';
					}
				},
				{
					dataIndex: 'name',
					text: 'File',
					flex: 1
				}
			]
		};

		// Check to add pagingbar
		if (o_initial.pagingbar !== false) {
			o_config.dockedItems = Ext.Array.merge([], o_initial.dockedItems || [], [{
				xtype: 'extendedpagingtoolbar',
				itemId: 'pagingbar',
				store: i_store,
				dock: o_initial.pagebarPosition || i_cmp.pagebarPosition,
				pageSearch: o_initial.pagebarSearch || i_cmp.pagebarSearch,
				pageSearchWidth: o_initial.pagebarSearchWidth || i_cmp.pagebarSearchWidth,
				pageSearchEmptyText: o_initial.pagebarSearchEmptyText || i_cmp.pagebarSearchEmptyText,
				pageSizeEdit: o_initial.pagebarSizeEdit || i_cmp.pagebarSizeEdit
			}]);
		}

		// If we have columns passed in component configuration
		// And instanciator want to overwrite
		if (o_initial.columns && o_initial.overwriteColumns) {
			o_config.columns = o_initial.columns;
		}
		else if (o_initial.columns) {
			o_config.columns = Ext.Array.merge([], o_initial.columns || [], o_config.columns);
		}

		// Finally apply the configuration
		Ext.apply(i_cmp, o_config);

		// and call the parent constructor
		i_cmp.callParent();

		// Initialize any possible value(s) to place this/these item(s) first
		i_cmp.initValue();

		// Add Key navigation and interaction
		i_cmp.initKeyMapping();

		return i_cmp;
	},

	onEnterKey: function (i_record, n_index, e) {

		var i_cmp = this;

		i_cmp.doItemSelection();

		return i_cmp;
	},
	onRightKey: function (i_record, n_index, e) {

		var i_cmp = this;
		var b_pagingbar = i_cmp.pagebar;

		if (b_pagingbar) {
			i_cmp.down('#pagingbar').moveNext();
		}

		return i_cmp;
	},
	onLeftKey: function (i_record, n_index) {

		var i_cmp = this;
		var b_pagingbar = i_cmp.pagebar;

		if (b_pagingbar) {
			i_cmp.down('#pagingbar').movePrevious();
		}

		return i_cmp;
	},

	doItemSelection: function () {

		var i_cmp = this;
		var a_selected = i_cmp.getItemSelection();

		i_cmp.fireEvent('itemselect', i_cmp, a_selected);

		return i_cmp;
	},
	getItemSelection: function () {

		return this.getSelectionModel().getSelection();
	},

	initValue: function () {

		var i_cmp = this;
		var value = i_cmp.initialConfig.value;

		if (value) {
			i_cmp.setValue(value);
		}

		return i_cmp;
	},
	getValue: function () {

		return this.value;
	},
	setValue: function (value) {

		var i_cmp = this;
		var a_value = i_cmp.sanitizeValue(value);

		i_cmp.value = a_value;

		// Update the store proxy to handle a union of selected values
		i_cmp.updateStoreProxy();

		return i_cmp;
	},
	sanitizeValue: function (value) {

		var a_value = [];

		if (value) {
			a_value = (Ext.isArray(value)) ? value : [value];
		}

		return a_value;
	},

	updateStoreProxy: function () {

		var i_cmp = this;
		var i_store = i_cmp.getStore();
		var a_value = i_cmp.getValue();
		var a_union = [];

		Ext.Array.each(a_value, function (s_path, n_index) {
			a_union.push({
				property: 'path',
				value: s_path
			});
		});

		if (a_union.length) {
			i_store.proxy.extraParams.union = Ext.encode(a_union);
		}
		else {
			delete i_store.proxy.extraParams.union;
		}

		return i_cmp;
	}
});
