Ext.define("Ext.ux.folderorganizer.Itemgrid", {
	extend: "Ext.grid.Panel",
	alias: "widget.folderitemgrid",
	border: 0,
	multiSelect: true,
	autoScroll: true,
	collapable: false,
	selModel: {
		mode: "SINGLE"
	},
	config: {
		collection: {},
		hasAssociation: false,
		wrapper: null,
		cid: 0,
		namePrefix: "itemGrid",
		filter: [],
		uiName: "portfolio"
	},
	initComponent: function() {

		var i_self = this;

		var o_collection = i_self.getCollection();

		i_self.name = i_self.getNamePrefix() + "_grid";
		i_self.itemId = i_self.name;
		i_self.setHasAssociation(i_self.getWrapper() ? true : false);

		// collection information from xpd ?
		if (o_collection) {
			o_collection.dmdName = o_collection.dmd.split(".").shift();
			i_self.store = i_self.setupCollection();
		}

		if (!i_self.getStore()) {
			Ext.ux.folderorganizer.Alert({
				title: i_self.getI18N("invalidConfig"),
				msg: i_self.getI18N("missingConfigOptions")
			});
		}

		var i_store = i_self.getStore();

		i_store.on({
			beforeload: {
				fn: function(i_store, i_operation) {

					var i_proxy = i_store.getProxy();
					var o_extraParams = i_proxy.getExtraParams();

					if (i_self.filter) {
						var a_add = [];
						var a_filters = i_self.getFilter();
						Ext.Array.each(a_filters, function(o_filter) {
							if (o_filter.value) {
								var s_filter = o_filter.property + " = " + o_filter.value;
								a_add.push(s_filter);
							}
						});
						if (a_add.length > 0) {
							var s_where = a_add.join(" AND ");
							Ext.apply(o_extraParams, {
								where: s_where
							});
						}
					}

					delete o_extraParams.filter;

					var o_sorters = i_store.getSorters();

					var a_sort = [];
					var s_sort = "";

					Ext.Array.each(o_sorters.items, function(o_sort) {
						var s_sorter = o_sort.getProperty() + " " + o_sort.getDirection();
						a_sort.push(s_sorter);
					});
					var s_sort = a_sort.join(", ");
					o_extraParams.sort = s_sort;
					o_extraParams.dir = "";
				}
			}
		});

		var o_viewConfig = i_self.viewConfig;

		if (!o_viewConfig) {
			o_viewConfig = {
				copy: (i_self.copyNode === true) ? true : false,
				variableRowHeight: true
			};
			if (i_self.getHasAssociation()) {
				Ext.apply(o_viewConfig, {
					plugins: {
						ptype: "gridviewdragdrop",
						dragGroup: "organizerItems",
						enableDrag: true
					}
				});
			}
		}
		else {
			o_viewConfig.variableRowHeight = true;
		}

		i_self.columns = i_self.columns || i_self.getModelColumns();

		var i_model = i_store.getModel();

		delete i_self.buttons;

		i_self.callParent();

		i_self.on({
			afterrender: {
				fn: function(i_grid) {
					i_self.keyMapping();
					var i_toolbar = i_self.down("toolbar");
					if (i_toolbar && i_toolbar.hideLink) {
						i_toolbar.hideLink();
					}
				}
			},
			selectionchange: {
				fn: function(i_selectionModel, a_records) {
					if (a_records.length > 0) {
						var i_wrapper = i_self.getWrapper();
						i_wrapper.fireEvent("rowselection", i_self.getCid(), a_records);
					}
				}
			},
			itemcontextmenu: {
				fn: function(i_view, i_selected, i_html, index, i_event) {

					i_event.preventDefault();
					i_view.getSelectionModel().select(i_selected);

					var i_element = Ext.get(i_html);
					var o_coords = i_event.getXY();
					var i_record = i_selected;

					if (ip2.isAccessible("app." + i_self.collection.dmdName + ".data." + i_self.collection.entity + ".update") ||
						ip2.isAccessible("app." + i_self.collection.dmdName + ".data." + i_self.collection.entity + ".read")) {
						var i_menu = Ext.widget("menu", {
							items: [{
									xtype: "menuitem",
									text: ip2.i18n({
										da: "Redigér " + i_self.title.toLowerCase(),
										en: "Edit " + i_self.title.toLowerCase()
									}),
									iconCls: "pf-edit",
									handler: function() {

										var o_size = Ext.ux.file.util.Handler.getWindowSize();
										var o_collection = i_self.getCollection();

										var i_window = Ext.widget("window", {
											modal: false,
											animateTarget: i_element,
											closable: true,
											collapsible: true,
											resizable: true,
											width: o_size.width * 0.9,
											height: o_size.height * 0.9,
											layout: "fit"
										});

										var o_config = {
											dmd: o_collection.dmd,
											entityName: o_collection.entity
										};

										ip2.addChild(i_window, i_record, "update", o_config);
										i_window.mon(ip2.App, "entityupdate:" + o_collection.entity, function(i_record) {
											i_store.load();
										});
										i_window.show();
									}
								}
							]
						});
						i_menu.showAt([o_coords[0], o_coords[1]]);
					}
				}
			},
			nodeadded: {
				fn: function(i_node) {
					i_store.load();
				}
			},
			noderemoved: {
				fn: function(i_node) {
					i_store.load();
				}
			}
		});

		var i_toolbar = Ext.widget("entitytoolbar", {
			model: i_model,
			dmdInfo: {
				dmd: o_collection.dmd,
				entityName: o_collection.entity,
				uiName: o_collection.uiName || "portfolio"
			},
			entityInfo: ip2.dmd.getInfo({
				dmd: o_collection.dmd || "dmd/webshop.dmd",
				view: o_collection.uiName || "portfolio",
				entity: o_collection.entity,
				context: "grid"
			}),
			store: i_self.getStore(),
			grid: i_self,
			dock: "top",
			hasExport: false,
			allowNew: false
		});

		i_self.addDocked(i_toolbar);

		i_store.load();
	},

	/* ----------------------------------------------------------------------------------------------------
	Add new row
	---------------------------------------------------------------------------------------------------- */
	addRow: function() {
		alert("add");
	},

	/* ----------------------------------------------------------------------------------------------------
	Refresh the view
	---------------------------------------------------------------------------------------------------- */
	refresh: function() {

		var i_self = this;
		var i_store = i_self.getStore();
		i_store.load();
	},

	/* ----------------------------------------------------------------------------------------------------
	Calculate and return the paging limit depending on the area available
	---------------------------------------------------------------------------------------------------- */
	getPagingLimit: function() {

		var i_self = this;
		var height = 0;
		var limit = 0;
		if (i_self.ownerCt && i_self.ownerCt.getHeight) {
			// does the grid lives inside an container ?
			height = i_self.ownerCt.getHeight();
		}
		if (height == 0) {
			height = ip2.body.init().getHeight();
		}
		height = height - i_self.headerHeight;

		// calculate page size
		limit = Math.floor(height / i_self.rowHeight);
		return limit;
	},

	/* ----------------------------------------------------------------------------------------------------
	Create grid columns
	---------------------------------------------------------------------------------------------------- */
	getModelColumns: function() {

		var i_self = this;
		var i_store = i_self.getStore();
		var i_model = i_store.getModel();
		var o_model = Ext.apply({}, i_model.prototype.dmdModel);
		var i_wrapper = i_self.getWrapper();
		var o_collection = i_self.getCollection();
		var s_uiName = i_self.getUiName();
		var a_gridcolumns = [];
		var a_displayColumns = i_self.displayColumns || [];

		Ext.Array.each(a_displayColumns, function(s_column) {
			s_column = s_column;
		});

		if (o_collection) {
			if (o_collection.uiName) {
				s_uiName = o_collection.uiName;
				a_gridcolumns = i_self.createGridColumnUI(s_uiName, a_displayColumns);
			}
			else {
				Ext.Object.each(o_collection.properties, function(s_key, o_property) {
					if (o_property.databasebind) {

						var o_column = i_self.applyGridColumnInformation({
							name: o_property.databasebind,
							title: ip2.xpd.translate(o_collection, o_property.title)
						});
						a_gridcolumns.push(o_column);
					}
				});
			}

			// if columns still empty, try to find isTitle fields
			if (Ext.isEmpty(a_gridcolumns)) {

				Ext.Object.each(o_collection.properties, function(s_key, o_property) {
					if (o_property.isTitle) {

						var o_column = i_self.applyGridColumnInformation({
							name: s_key,
							title: ip2.xpd.translate(i_wrapper.xpd, o_property.title)
						});

						o_column.header = o_column.title;
						o_column.dataIndex = o_collection.propertyFieldName;

						o_column.renderer = function(value, i_meta, i_record, n_rowIndex, n_colIndex) {

							var i_column = this.columns[n_colIndex];
							var s_field = o_collection.propertyFieldName;
							var s_property = i_record.get(s_field);
							var o_property = {};

							if (s_property) {
								o_property = Ext.decode(s_property, true) || {};
							}

							if (o_property[i_column.name]) {
								value = o_property[i_column.name];
							}

							return value;
						};
						a_gridcolumns.push(o_column);
					}
				});
			}
		}
		else {
			a_gridcolumns = i_self.createGridColumnUI(s_uiName, a_displayColumns);
		}

		// if columns still empty, use all fields
		if (Ext.isEmpty(a_gridcolumns)) {
			var columns = o_model.columns;

			var a_columns = [];
			if (Ext.isArray(columns)) {
				a_columns = columns.slice();
			}
			else {
				Ext.Object.each(columns, function(s_key, o_column) {

					var o_clone = Ext.apply({}, o_column);
					o_clone.name = s_key;
					a_columns.push(o_clone);
				});
			}

			Ext.Array.each(a_columns, function(o_column) {
				a_gridcolumns.push(o_column);
			});
		}

		return a_gridcolumns;
	},

	/* ----------------------------------------------------------------------------------------------------
	Create grid column UI
	---------------------------------------------------------------------------------------------------- */
	createGridColumnUI: function(s_uiName, displayColumns) {

		var i_self = this;
		var o_uiTypes = ip2.loadUItypes();
		var i_store = i_self.getStore();
		var i_model = i_store.getModel();
		var o_model = Ext.apply({}, i_model.prototype.dmdModel);
		var o_entity = Ext.apply({}, i_model.prototype.entity);
		var a_return = [];

		var o_view = o_entity.ui.grids[s_uiName] || o_entity.ui.grids.portfolio;
		var a_columns = o_view.columns.slice();

		Ext.Array.each(a_columns, function(o_column) {

			var o_clone = Ext.apply({}, o_column);

			if (o_clone.hide) {
				return true;
			}

			if (o_clone.from && !Ext.String.startsWith(o_clone.from, "(")) {
				o_clone.name = o_clone.from + "_" + o_clone.name;
			}

			if (o_clone.uitype) {
				var o_type = o_uiTypes[o_clone.uitype];
				if (o_type) {
					var o_grid = o_type.grid;
					if (o_grid && o_grid.renderer) {
						o_clone.renderer = o_grid.renderer;
					}
				}
			}

			if (!o_clone.renderer) {
				o_clone.renderer = function(value, metaData, record, rowIndex, colIndex, store) {
					if (Ext.isString(value) && Ext.String.startsWith(value, "{")) {
						return ip2.i18n(value);
					}
					return value;
				};
			}
			a_return.push(i_self.applyGridColumnInformation(o_clone));
		});

		return a_return;
	},

	/* ----------------------------------------------------------------------------------------------------
	Apply grid column information
	---------------------------------------------------------------------------------------------------- */
	applyGridColumnInformation: function(o_config) {

		var i_self = this;
		var i_store = i_self.getStore();
		var i_model = i_store.getModel();
		var o_model = i_model.prototype.dmdModel;
		var o_entity = i_model.prototype.entity;
		var o_columns = i_model.prototype.columns;
		var a_columns = [];

		if (Ext.isArray(o_config.name)) {

			o_config.titleFields = o_config.name;

			o_config.renderer = function(value, i_meta, i_record, n_rowIndex, n_colIndex) {

				var i_column = this.columns[n_colIndex];
				var s_property = i_record.get("PROPERTIES");
				var o_property = {};

				if (s_property) {
					o_property = Ext.decode(s_property, true) || {};
				}

				Ext.Array.each(o_config.name, function(s_name) {
					if (o_property[s_name]) {
						value = o_property[s_name];
						return false;
					}
				});

				if (o_property[i_column.name]) {
					value = o_property[i_column.name];
				}

				return value;
			};
			o_config.dataIndex = "PROPERTIES";
		}
		else {
			o_config.dataIndex = o_config.name;
		}

		if (Ext.isObject(o_columns)) {

			Ext.Object.each(o_columns, function(s_key, o_column) {

				var o_clone = Ext.apply({}, o_column);
				o_clone.name = s_key;
				a_columns.push(o_clone);
			});
		}
		else {
			a_columns = o_columns.slice();
		}

		var o_field = {
			column: {}
		};;

		Ext.Array.each(a_columns, function(o_column) {
			if (o_config.dataIndex == o_column.name) {
				o_field.column = o_column;
				return false;
			}
		});

		// set column width / flex
		if (!o_config.width) {
			o_config.flex = 1;
		}

		Ext.applyIf(o_config, o_field.column);

		if (o_config.dataIndex == "PROPERTIES" && o_config.title) {
			o_config.header = o_config.title;
		}

		// Translate the o_config header
		if (o_config.header) {
			var s_title = o_config.header;
			if (Ext.isObject(s_title)) {
				o_config.header = ip2.dmdTranslate(o_model, s_title);
			}
		}
		else if (o_config.title) {
			var s_title = o_config.title;
			if (Ext.isObject(s_title)) {
				o_config.header = ip2.i18n(s_title);
			}
			else {
				o_config.header = s_title;
			}
		}

		return o_config;
	},

	/* ----------------------------------------------------------------------------------------------------
	Setup using collection information from xpd
	---------------------------------------------------------------------------------------------------- */
	setupCollection: function() {

		var i_self = this;
		var i_wrapper = i_self.getWrapper();
		var o_collection = i_self.getCollection();
		var a_sorters = [];

		var properties = function() {
			//"filter": "jsonPropsIn(properties, "__cid__", "5,6") = 1",
			var args = Array.prototype.slice.call(arguments);
			var cids = args.join(",");
			return "jsonPropsIn(" + me.collection.propertyFieldName + ", \"__cid__\", \"" + cids + "\") = 1";
		};

		var s_title = i_self.title || ip2.xpd.translate(i_wrapper.xpd, i_self.collection.title);

		i_self.setNamePrefix("hasMany");
		i_self.setTitle(s_title);
		i_self.iconCls = "ip2-tree-application-group";
		i_self.setCid(o_collection.id);

		if (o_collection.xpdbind) {
			i_self.setFilter(eval(o_collection.xpdbind));
		};

		var i_model = ip2.model({
			dmd: o_collection.dmd,
			entityName: o_collection.entity,
			uiName: o_collection.uiName || "portfolio",
			context: o_collection.context || "grid",
			dataLibrary: (i_wrapper && i_wrapper.wrapper && Ext.isFunction(i_wrapper.wrapper.getDataLibrary)) ? i_wrapper.wrapper.getDataLibrary() : "",
			container: i_wrapper.wrapper.ownerCt
		});

		var o_params = {
			action: "getRows",
			context: "grid",
			uiName: o_collection.uiName || "portfolio",
			dmdFile: o_collection.dmd || "dmd/webshop.dmd",
			language: o_collection.languageColumn ? ip2.session.getLanguage() : "",
			languageColumn: o_collection.languageColumn || ""
		};


		if (i_self.getCid()) {

			var a_fields = i_model.getFields();

			var i_cidField = Ext.create("Ext.data.Field", {
				name: "cid",
				type: "int"
			});

			a_fields.push(i_cidField);

			i_model.addFields(a_fields);

			var o_extraData = [{
				"property": "cid",
				"value": i_self.getCid()
			}];

			o_params.extraData = Ext.encode(o_extraData);
		}

		if (o_collection.entity) {
			var o_info = ip2.dmd.getInfo({
				dmd: o_collection.dmd || "dmd/webshop.dmd",
				view: o_collection.uiName,
				entity: o_collection.entity,
				context: "grid"
			});
			var o_ui = o_info.view;

			//var ui = ip2.entity.getUI(o_collection.entity, "grids", o_collection.uiName);
			if (o_ui.sort) {
				o_params.sort = o_ui.sort;
				a_sorters = Ext.Array.map(o_ui.sort.split(","), function (s_value) {
					var a_split = Ext.Array.filter(s_value.split(" "), Boolean);
					return {
						property: a_split[0],
						direction: a_split[1] ? a_split [1] : "ASC"
					};
				});
			}
		}

		var i_store = Ext.create("Ext.data.BufferedStore", {
			model: i_model,
			sorters: a_sorters,
			remoteSort: true,
			autoSync: false,
			pageSize: 100,
			proxy: ip2.getProxyByEntity({
				dmd: o_collection.dmd || "dmd/webshop.dmd",
				view: o_collection.uiName,
				entity: o_collection.entity,
				context: "grid"
			})
		});

		var i_proxy = i_store.getProxy();
		var o_extraParams = i_proxy.getExtraParams();
		Ext.apply(o_extraParams, o_params);

		return i_store;
	},

	/* ----------------------------------------------------------------------------------------------------
	Keyboard mapping (short-cut)
	---------------------------------------------------------------------------------------------------- */
	keyMapping: function() {

		var i_self = this;

		var i_keyMap = Ext.create("Ext.util.KeyMap", {
			target: i_self.getEl(),
			binding: [
				{
					key: "b",
					ctrl: true,
					fn: function() {
						i_self.addRow();
					},
					scope: this,
					defaultEventAction: "stopEvent"

				}
			]
		});
	},

	/* ----------------------------------------------------------------------------------------------------
	Set focus
	---------------------------------------------------------------------------------------------------- */
	setFocus: function(s_component) {

		var i_self = this;

		if (s_component == "grid") {
			var selModel = i_self.getSelectionModel();
			i_self.getView().focus();
			selModel.select(0);
			var records = selModel.getSelection();
			i_self.fireEvent("selectionchange", selModel, records);
		}
		else {
			if (!i_self[s_component]) {
				return false;
			}

			i_self[s_component].focus();
		}

		return true; // set focus successed
	},

	/* ----------------------------------------------------------------------------------------------------
	Get the i18n text
	---------------------------------------------------------------------------------------------------- */
	getI18N: function(key) {
		return (ip2.folderorganizer) ? ip2.folderorganizer.getTextValue(key) : key;
	}
});
