Ext.define("Portfolio.designer.ui.domainModelEntityKeyGrid", {
	extend: "Ext.grid.Panel",
	alias: ["widget.ip2DomainModelEntityKeyGrid"],

	config: {
		entity: null,
		entityManager: null,
		selector: null,
		rowMenu: null,
		required: false
	},

	requires: [
		"Portfolio.designer.model.domainModelEntityKeyManagerDataModel"
	],

	initComponent: function() {

		var i_self = this;

		var o_entity = i_self.getEntity() || {};

		i_self.valid = true;

		// grid columns
		i_self.columns = i_self.createColumns();
		i_self.store = i_self.createStore();

		// toolbar
		i_self.tbar = [
			{
				xtype: "button",
				text: ip2.i18n("addNew"),
				iconCls: "pf-add",
				disabled: i_self.required,
				handler: function() {

					var i_store = i_self.getStore();
					var n_count = i_store.getCount();
					var i_model = i_store.getModel();
					var i_selector = i_self.getSelector();

					var i_record = i_model.create({
						name: ip2.unique("keyindex-")
					});

					i_store.add(i_record);

					var i_plugin = i_self.getPlugin("celledit");

					i_plugin.startEditByPosition(
						{
							row: n_count,
							column: 0
						}
					);

					i_selector.show();
				}
			}
		];

		var i_cellPlugin = Ext.create("Ext.grid.plugin.CellEditing", {
			pluginId: "celledit",
			clicksToEdit: 1,
			listeners: {
				beforeedit: {
					fn: function() {
						return !i_self.required;
					}
				},
				edit: {
					fn: function(i_editor, o_context) {

						var i_store = i_self.getStore();
						var a_records = i_store.getRange();
						var i_entityManager = i_self.getEntityManager();

						if (o_context.field == "primary" && o_context.value) {

							Ext.Array.each(a_records, function(i_record) {
								if (i_record.get("primary") && i_record.id != o_context.i_record.id) {
									i_record.set("primary", false);
								}
							});
						}

						if (o_context.record.dirty) {
							if (o_context.field == "name" && o_context.record.modified.name) {
								if (o_context.record.data.name != o_context.record.modified.name && o_context.record.data.was.length === 0) {
									o_context.record.set("was", o_context.record.modified.name);
								}
							}
						}
						o_context.record.commit();
					}
				}
			}
		});

		i_self.plugins = i_cellPlugin;

		i_self.callParent();

		i_self.on({
			select: {
				fn: function(i_view, i_record, i_html, n_index, i_event) {

					var i_self = this;
					var i_selector = i_self.getSelector();

					var i_entityManager = i_self.getEntityManager();
					var i_columnManager = i_entityManager.getColumnManager();
					var i_columnGrid = i_columnManager.getColumnGrid();
					var i_store = i_columnGrid.getStore();

					i_selector.selector.bindStore(i_store, true);

					i_selector.setToField(i_record.get("columns"));

					i_selector.show();
					i_record.commit();
				}
			},
			itemcontextmenu: {
				fn: function(i_view, i_record, i_html, n_index, i_event) {

					i_event.stopEvent();

					var a_coords = i_event.getXY();

					var i_menu = Ext.create("Ext.menu.Menu", {
						items: [
							{
								xtype: "menuitem",
								text: ip2.i18n({
									da: "Slet",
									en: "Delete"
								}),
								iconCls: "pf-delete",
								disabled: i_self.required,
								handler: function() {
									i_self.deleteRow();
								}
							}
						]
					});

					i_menu.showAt(a_coords[0], a_coords[1]);
				}
			},
			validateedit: {
				fn: function(i_editor, o_context) {

					i_self.valid = true;
					var b_valid = true;
					var i_store = i_self.getStore();
					var a_records = i_store.getRange();

					// validate name column
					if (o_context.field == "name") {

						Ext.Array.each(a_records, function(i_record) {
							if (o_context.record != i_record && o_context.value.toLowerCase() == i_record.get("name").toLowerCase()) {
								b_valid = false;
								return false;
							}
						});
					}

					return b_valid;
				}
			}
		});
	},

	createColumns: function() {

		var i_self = this;

		var a_columns = [
			{
				header: ip2.i18n("name"),
				dataIndex: "name",
				flex: 1,
				editor: {
					xtype: "textfield"
				}
			},
			{
				header: ip2.i18n("keyFields"),
				dataIndex: "columns",
				flex: 4,
				renderer: i_self.columnArray2StringRenderer
			},
			{
				header: ip2.i18n("primary"),
				dataIndex: "primary",
				align: "center",
				xtype: "checkcolumn",
				listeners: {
					checkchange: {
						fn: function(i_column, n_rowIndex, b_checked) {

							var i_store = i_column.ownerCt.grid.getStore();
							var i_record = i_store.getAt(n_rowIndex);

							i_record.set("primary", b_checked);
							i_record.commit();
						}
					}
				}
			}
		];

		return a_columns;
	},

	createStore: function() {

		var i_self = this;
		var o_entity = i_self.getEntity();

		var a_data = [];

		o_entity.keys = o_entity.keys || [];

		if (Ext.isObject(o_entity.keys)) {

			Ext.Object.each(o_entity.keys, function(s_key, o_value) {
				a_data.push(o_value);
			});
		}

		if (Ext.isArray(o_entity.keys)) {
			a_data = o_entity.keys;
		}

		var i_store = Ext.create("Ext.data.Store", {
			model: "Portfolio.designer.model.domainModelEntityKeyManagerDataModel",
			data: a_data
		});

		return i_store;
	},

	columnArray2StringRenderer: function(a_value, i_meta, i_record) {

		var i_self = this;
		var o_entity = i_self.getEntity();

		if (!Ext.isArray(a_value)) {
			return "";
		}

		var a_join = [];

		Ext.Array.each(a_value, function(o_value) {

			var s_value = o_value;

			if (Ext.isObject(o_value)) {
				Ext.Array.each(o_entity.columns, function(o_column) {
					if (o_column.name === o_value.name) {
						a_join.push(o_column.name + " (" + ip2.i18n(o_column.title) + ")");
					}
				});
			}
			else {
				a_join.push(s_value);
			}
		});

		return a_join.join(", ");
	},

	deleteRow: function() {

		var i_self = this;
		var i_store = i_self.getStore();
		var i_selector = i_self.getSelector();

		var a_records = i_self.getSelectionModel().getSelection();
		var i_record = a_records[0];

		ip2.messageBox({
			title: ip2.i18n({
				da: "Bekræft slet",
				en: "Confirm Delete"
			}),
			message: ip2.i18n({
				da: "Er du sikker på du vil slette..?",
				en: "Are you sure you want to delete"
			}),
			yesText: ip2.i18n({
				da: "Ja",
				en: "Yes"
			}),
			noText: ip2.i18n({
				da: "Nej",
				en: "No"
			}),
			yesFn: function () {
				i_selector.hide();
				i_store.remove(i_record);
				i_self.getSelectionModel().select(0);
			}
		});
	},

	isValid: function() {
		return true;
	}
});
