Ext.define("Ext.ux.stackorganizer.view.ContentGrid", {

	extend: "Ext.grid.Panel",

	alias: ["widget.stackcontentgrid"],

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

	xpd: "",

	supportXpd: "",

	tokenKey: null,

	collection: null,

	stack: null,

	stackId: null,

	filter: null,

	originalFilter: null,

	initComponent: function () {

		var i_cmp = this;
		var o_config = i_cmp.initialConfig;

		var s_supportXpd = o_config.supportXpd;
		var o_supportXpd = i_cmp.sanitizeXpdValue(s_supportXpd);

		Ext.apply(i_cmp, {
			viewConfig: {
				plugins: {
					ptype: "gridviewdragdrop",
					enableDrag: true,
					dragGroup: "grid2tree",
					allowContainerDrops: false
				}
			},
			columns: [
				{
					xtype: "themedactioncolumn",
					text: ip2.i18n({
						da: "Tilføj",
						en: "Add"
					}),
					iconCls: "pf-add",
					width: 50,
					handler: function (i_view, n_row, n_col, o_item, o_event) {

						var i_store = i_cmp.getStore();
						var i_record = i_store.getAt(n_row);

						i_cmp.fireEvent("stackadd", i_cmp, i_record, true);
					},
					tdCls: "x-ux-stack-column-action"
				},
				{
					text: ip2.i18n({
						da: "Stak ID",
						en: "Stack ID"
					}),
					hidden: true,
					dataIndex: "stackId"
				},
				{
					xtype: "stackiconcolumn",
					text: ip2.i18n({
						da: "Type",
						en: "Type"
					}),
					dataIndex: "ptype",
					width: 110
				},
				{
					xtype: "stackpropertiescolumn",
					dataIndex: "toplink",
					text: ip2.i18n({
						da: "Specifikationer",
						en: "Specifications"
					}),
					flex: 1
				}
			],
			dockedItems: [
				{
					xtype: "toolbar",
					height: 30,
					items: [
						{
							xtype: "button",
							iconCls: "pf-refresh",
							handler: function () {
								i_cmp.refreshData();
							}
						},
						"-",
						{
							xtype: "textfield",
							itemId: "searchfield",
							size: 40,
							enableKeyEvents: true,
							margin: "0 0 0 5",
							isFormField: false,
							onClear: function() {
								this.setValue("");
								this.getTrigger("clear").hide();
								i_cmp.refreshData();
							},
							onRefresh: function() {
								var value = this.getValue();
								if (!value) {
									this.getTrigger("clear").hide();
								}
								else {
									this.getTrigger("clear").show();
								}
								i_cmp.refreshData();
							},
							triggers: {
								clear: {
									weight: 1,
									cls: "x-form-clear-trigger",
									scope: "this",
									hidden: true,
									handler: "onClear"
								},
								search: {
									weight: 1,
									cls: "x-form-search-trigger",
									scope: "this",
									handler: "onRefresh"
								}
							},
							listeners: {
								"specialkey": {
									fn: function (i_self, e) {
										if (e.getKey() == e.ENTER) {
											value = this.getValue();
											if (!value) {
												this.getTrigger("clear").hide();
											}
											else {
												this.getTrigger("clear").show();
											}
											i_cmp.refreshData();
										}
									}
								}
							}
						}
					]
				}
			],
			supportXpd: o_supportXpd
		});

		i_cmp.callParent(arguments);

		i_cmp.on("itemdblclick", function (i_grid, i_record) {
			i_cmp.fireEvent("stackadd", i_cmp, i_record, true);
		});

		// Set the original filter
		var a_filter = i_cmp.getFilter();
		i_cmp.originalFilter = a_filter;

		i_cmp.on("afterrender", i_cmp.onAfterrender);

		i_cmp.initKeyMapping();

		return i_cmp;
	},

	sanitizeXpdValue: function (xpd) {

		if (Ext.isString(xpd)) {
			xpd = ip2.resource.get(xpd, true);
		}

		return xpd;
	},

	getModel: function() {

		var i_self = this;
		var o_collection = i_self.collection;
		var i_model = ip2.model({
			dmd: o_collection.dmd,
			entityName: o_collection.entity,
			uiName: "portfolio",
			context: "form"
		});
		return i_model;
	},

	onAfterrender: function () {

		var i_cmp = this;
		var i_store = i_cmp.getStore();

		i_cmp.loadItems(function (a_items) {
			i_store.loadData(a_items);
		});

		return i_cmp;
	},

	setStack: function (o_stack) {

		var i_cmp = this;

		i_cmp.stack = o_stack;

		i_cmp.refreshData();

		return i_cmp;
	},

	getFilter: function () {

		var i_cmp = this;
		var i_store = i_cmp.getStore();
		var o_collection = i_cmp.collection;
		var o_stack = i_cmp.stack;
		var a_tokens = [];
		var a_filter;

		// Check if the collection is the same as the root
		// Add that token or 0 if so
		if (o_collection.ptype == o_stack.ptype) {
			a_tokens.push(o_stack.token || 0);
		}

		Ext.Array.each(o_stack.children, function(o_child) {
			if (o_collection.ptype == o_child.ptype) {
				a_tokens.push(o_child.token);
			}
		});

		if (a_tokens.length) {
			o_stack = Ext.Object.merge({
				tokens: a_tokens.join(", ")
			}, o_stack);
		}
		else {
			delete o_collection.properties.token;
		}

		i_model = ip2.model({
			dmd: o_collection.dmd,
			entityName: o_collection.entity,
			context: "grid",
			uiName: "portfolio"
		});

		var a_filters = ip2.xpd.createFilter(o_collection, o_stack);
		if (a_tokens.length > 0) {
			var b_found = false;
			ip2.each(a_filters, function(o_filter) {
				if (o_filter.property == i_model.idProperty) {
					b_found = true;
				}
			});
			if (!b_found) {
				var o_filter = {
					property: i_model.idProperty,
					where: "not in (" + a_tokens.join(", ") + ")"
				};
				a_filters.push(o_filter);
			}
		}

		return a_filters;
	},
	getOriginalFilter: function () {

		return this.originalFilter;
	},
	isFilterDirty: function () {

		var i_cmp = this;
		var a_original = i_cmp.getOriginalFilter();
		var a_filter = i_cmp.getFilter();

		if (a_original === null || a_filter === null) {
			return false;
		}

		return ip2.isEqual(a_original, a_filter);
	},

	loadItems: function (f_callback) {

		f_callback = f_callback || Ext.emptyFn;

		var i_cmp = this;
		var o_supportXpd = i_cmp.supportXpd;
		var s_xpdPath = o_supportXpd._path;

		var o_collection = i_cmp.collection;
		var s_ptype = o_collection.ptype;
		var n_stackId = i_cmp.stackId;
		var s_search = i_cmp.down("#searchfield").getValue();

		var a_filter = i_cmp.getFilter();
		var s_filter = Ext.encode(a_filter);

		var o_params = {
			xpd: s_xpdPath,
			action: "getStackContent",
			ptype: s_ptype,
			stackId: n_stackId,
			filter: s_filter,
			uiName: "portfolio",
			context: "grid"
		};

		if (s_search.length) {
			o_params.search = s_search;
		}

		// Load the list data and add the initialize the components
		Ext.Ajax.request({
			url: "/wsh-services/wshproxy.aspx",
			params: o_params,
			success: function (o_response) {

				var a_items = [];

				try {
					a_items = Ext.decode(o_response.responseText);
				}
				catch (err) {
					console.log("TODO: Error handling via IP2 for Ext.ux.stackorganizer.ContentGrid on loadData method");
				}

				f_callback(a_items);
			}
		});

		return i_cmp;
	},

	refreshData: function (i_record) {

		var i_cmp = this;
		var i_store = i_cmp.getStore();
		var i_view = i_cmp.getView();
		var s_search = i_cmp.down("#searchfield").getValue();
		var i_add = null;

		i_cmp.setLoading(true);
		i_cmp.loadItems(function (a_items) {
			i_cmp.setLoading(false);
			i_store.loadData(a_items);
			if (i_record) {
				ip2.each(i_store.data.items, function(i_item) {
					if (i_item.get("token") == i_record.get(i_record.idProperty)) {
						i_add = i_item;
					}
				});
			}

			if (i_add) {
				i_cmp.fireEvent("stackadd", i_cmp, i_add, true);
			}
		});

		return i_cmp;
	}
});
