Ext.define("Portfolio.designer.ui.domainModelEntityColumnCommonProperties", {
	extend: "Ext.grid.property.Grid",
	alias: ["widget.ip2DomainModelEntityColumnCommonProperties"],
	border: false,
	sortableColumns: false,

	config: {
		entityManager: null,
		designer: null,
		customRenderers: {},
		customEditors: {},
		propertyNames: {},
		properties: {},
		entity: {},
		record: null
	},

	requires: [
		"Portfolio.designer.ui.EditcodeComboBox"
	],

	initComponent: function() {

		var i_self = this;
		var i_designer = i_self.getDesigner();
		var o_normal = i_designer.normal;

		var o_customRenderers = i_self.getCustomRenderers();
		var o_customEditors = i_self.getCustomEditors();
		var i_entityManager = i_self.getEntityManager();

		var o_fields = {};
		var o_types = o_normal.types || {};
		var o_generic = o_normal.generic || {};

		Ext.Object.each(o_types, function(s_key, o_type) {

			var a_properties = o_type.properties || [];

			Ext.Object.each(o_generic, function(s_key, o_value) {

				var b_found = Ext.Array.findBy(a_properties, function(o_property) {
					return o_property.name == s_key;
				});

				if (!b_found) {
					a_properties.push(o_value);
				}
			});

			o_type.properties = a_properties;
		});

		Ext.Object.each(o_types, function(s_type, o_type) {

			Ext.Array.each(o_type.properties, function(o_property) {

				if (o_property.editor) {

					var o_field = Ext.Object.merge({}, {
						name: o_property.name,
						dependingOn: o_property.dependingOn || {},
						model: i_designer.model,
						designer: i_designer,
						entityManager: i_entityManager,
						propertyGrid: i_self,
						listeners: {}
					}, o_property.editor);

					if (o_field.xtype == "ip2DomainModelColumnTypeComboBox") {

						Ext.apply(o_field.listeners, {
							select: {
								fn: function(i_field, i_selected) {

									var s_type = i_selected.get("key");
									var i_record = i_self.getRecord();

									i_record.set("type", s_type);
									i_record.set("len", 0);

									var o_template = o_type;
									var o_defaults = o_template.defaults || {};

									Ext.Object.each(o_defaults, function(s_key, value) {
										i_record.set(s_key, o_defaults[s_key]);
									});

									i_self.updateValues(i_record);
								}
							}
						});
					}
					else if (o_field.xtype == "ip2DomainModelExtendFieldComboBox") {

						Ext.apply(o_field.listeners, {
							select: {
								fn: function(i_field, i_selected) {

									var i_record = i_self.getRecord();

									i_record.set("from", i_selected.get("name"));
									i_record.set("name", i_selected.get("name"));
									i_record.set("title", i_selected.get("title"));

									i_self.updateValues(i_record);
								}
							}
						});
					}

					else if (o_field.xtype == "i18n-textfield") {
						o_customRenderers[o_field.name] = function(v) {
							return ip2.i18n(v);
						};
					}
					else if (o_field.xtype == "comboinline") {

						var i_field = Ext.widget(o_field.xtype, o_field);
						o_customRenderers[o_field.name] = function(v) {
							return i_field.renderer(v);
						};
					}
					else if (o_field.xtype == "ip2DomainModelHookEnumComboBox") {
						o_customRenderers[o_field.name] = function(v) {
							var enums = (ip2.baseConfig.ns.adm.enums.i18nhook) ? ip2.baseConfig.ns.adm.enums.i18nhook.values : {};
							return enums[v][ip2.getUserLanguageCode()];
						};
					}

					o_fields[o_property.name] = o_field;
				}
			});
		});

		Ext.Object.each(o_fields, function(s_field, o_field) {
			o_customEditors[s_field] = o_fields[s_field];
		});

		i_self.callParent();

		i_self.on({
			propertychange: {
				fn: function(source, recordId, value) {

					var i_record = i_self.getRecord();

					var i_entityManager = i_self.getEntityManager();

					if (i_record) {

						var originalValue = i_record.get(recordId);

						i_self.suspendEvents();
						i_self.setProperty(recordId, value);
						i_self.resumeEvents();

						if (i_record) {
							i_record.set(recordId, value);
						}

						var b_needSync = false;

						if (recordId == "name") {
							if (value != originalValue) {
								i_record.set("was", originalValue);
								i_self.syncColumnName(value, originalValue);
								b_needSync = true;
							}
						}
						else {
							if (recordId == "title") {
								var s_idProperty = i_record.get(i_record.idProperty);
								i_self.syncProperty(s_idProperty, recordId, value, originalValue);
								b_needSync = true;
							}
						}
						i_record.commit();

						if (i_entityManager) {
							var i_propertyManager = i_entityManager.getEntityPropertyManager();

							var i_columnManager = i_entityManager.getColumnManager();

							var a_records = i_columnManager.columnGrid.getStore().getRange();

							i_propertyManager.fireEvent("datachanged", a_records, i_record);

							if (b_needSync) {
								i_self.syncUI();
							}
						}
					}
				}
			}
		});
	},

	syncUI: function() {

		var i_self = this;
		var i_entityManager = i_self.getEntityManager();

		if (i_entityManager && i_entityManager.getFormDesigner() && i_entityManager.getViewManager()) {

			var i_formDesigner = i_entityManager.getFormDesigner();
			var i_viewManager = i_entityManager.getViewManager();

			i_formDesigner.fireEvent("newColumns", i_formDesigner, i_entityManager.getNewColumns());
			i_viewManager.fireEvent("newColumns", i_viewManager, i_entityManager.getNewColumns());
		}
	},

	updateValues: function(i_record) {

		var i_self = this;
		var o_data = i_record.getData();

		var i_designer = i_self.getDesigner();
		var o_normal = i_designer.normal;
		var o_types = o_normal.types;
		var s_type = o_data.from ? "extention" : o_data.like ? "like" : o_data.type ? o_data.type : "new";
		var o_template = o_types[s_type];
		var a_disabled = [];

		var o_properties = {};

		o_properties = {};

		if (o_template) {
			switch (s_type) {
				case "like":

					var o_baseDataTypes = o_types[i_record.get("like")];

					Ext.Object.each(o_baseDataTypes, function(s_key, o_value) {

						var o_field = Ext.apply({}, {
							name: s_key
						});

						o_template.properties.push(o_field);

						i_record.set(s_key, o_baseDataTypes[s_key]);
						a_disabled.push(s_key);
					});

					break;
			}

			Ext.Array.each(o_template.properties, function(o_property) {

				var s_property = o_property.name;

				var boolean = false;

				switch (name) {
					case "syncBoth" :
					case "isRowId" :
					case "isTitle" :
					case "isMandatory" :
					case "protected":
					case "inheritance":
						boolean = true;
						break;
					default:
						break;
				}
				var value;

				if (s_property == "title") {
					value = i_record.get(s_property);
				}
				else {
					value = (s_property == "type" && s_type == "extention") ? s_type : i_record.get(s_property) ? i_record.get(s_property) : (boolean) ? false : "";
				}

				var b_disabled = true;
				if (o_property.dependingOn && o_property.dependingOn.field) {
					if (i_record.get(o_property.dependingOn.field) != o_property.dependingOn.value) {
						b_disabled = false;
						i_record.get(s_property) = "";
					}
				}

				if (b_disabled) {
					o_properties[s_property] = value;
				}

				var o_editor = i_self.customEditors[s_property];
				if (o_editor) {
					o_editor.disabled = false;
				}
			});
		}

		var i_plugin = i_self.getPlugins()[0];

		i_plugin.editors.clear();

		i_self.suspendEvents();
		i_self.setSource(o_properties);
		i_self.resumeEvents();

		i_self.closeProperties(a_disabled);
		i_self.fireEvent("propertyupdate", i_self);
	},

	closeProperties: function(a_properties) {

		var i_self = this;
		var o_customEditors = i_self.getCustomEditors();

		Ext.Array.each(a_properties, function(s_key) {
			var o_editor = o_customEditors[s_key];
			if (o_editor) {
				o_editor.disabled = true;
			}
		});
	},

	syncProperty: function(s_idProperty, s_property, value, originalValue) {

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

		if (i_entityManager && i_entityManager.getFormDesigner() && i_entityManager.getViewManager()) {

			var i_viewManager = i_entityManager.getViewManager();
			var i_formDesigner = i_entityManager.getFormDesigner();

			var a_forms = i_formDesigner.getForms();

			Ext.Array.each(a_forms, function(i_panel) {

				var i_tree = i_panel.getTreeGrid();
				var i_root = i_tree.getRootNode();

				var i_node = i_root.findChild("itemId", o_entity.name + "_" + s_idProperty, true);

				if (i_node) {
					var o_properties = i_node.get("properties");

					var o_values = {};
					var currentValue = Ext.clone(o_properties[s_property]);

					if (Ext.isObject(currentValue)) {
						currentValue = Ext.encode(currentValue);
					}

					if (Ext.isObject(originalValue)) {
						originalValue = Ext.encode(originalValue);
					}

					if (String(currentValue) === String(originalValue)) {

						if (Ext.isObject(value)) {

							Ext.Object.each(value, function(s_key, s_value) {
								value[s_key] = String(s_value).trim();
							});
						}

						o_values[s_property] = value;

						Ext.apply(o_properties, o_values);

						i_node.set({
							properties: o_properties
						});

						i_node.commit();
					}
				}
			});

			var a_grids = i_viewManager.getGrids();

			Ext.Array.each(a_grids, function(i_grid) {

				var a_columns = i_grid.getColumnManager().getColumns();

				Ext.Array.each(a_columns, function(i_column) {
					if (i_column.dataIndex == s_idProperty && i_column.entity == o_entity.name) {
						i_column.setText(ip2.i18n(value));
						i_column.columnConfig = i_column.columnConfig || i_column.initialConfig;
						i_column.columnConfig[s_property] = value;
						return false;
					}
				});
			});
		}
	},

	syncColumnName: function(newName, originalName) {

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

		if (i_entityManager && i_entityManager.getFormDesigner() && i_entityManager.getViewManager()) {

			var i_keyManager = i_entityManager.getKeyManager();
			var i_entityPropertyManager = i_entityManager.getEntityPropertyManager();
			var i_relationManager = i_entityManager.getRelationManager();

			var i_keyGrid = i_keyManager.keyGrid;

			var newValue = [];
			var changed = false;
			var value = "";

			originalName = originalName || "";

			// change column name in json object
			Ext.Array.each(o_entity, function(o_column) {
				if (o_column.name == originalName) {
					o_column.name = newName;
					return false; // end loop
				}
			});

			var i_idColumn = i_entityPropertyManager.getForm().findField("idColumn");

			if (i_idColumn.getValue()) {
				value = i_idColumn.getValue();
				if (Ext.isString(value)) {
					value = value.split(",");
				}
				Ext.Array.each(value, function(s_value) {
					if (originalName == s_value) {
						changed = true;
						newValue.push(newName);
					}
				});
				if (changed) {
					i_idColumn.setValue(newValue);
				}
			}

			newValue = [];
			changed = false;
			value = "";

			var i_priameryKey = i_entityPropertyManager.getForm().findField("primaryKey");

			if (i_priameryKey.getValue()) {
				value = i_priameryKey.getValue();
				if (Ext.isString(value)) {
					value = value.split(",");
				}
				Ext.Array.each(value, function(s_value) {
					if (originalName == s_value) {
						changed = true;
						newValue.push(newName);
					}
				});
				if (newValue.length > 0) {
					i_priameryKey.setValue(newValue);
				}
			}

			var i_storeKey = i_keyGrid.getStore();
			var a_keys = i_storeKey.getRange();

			Ext.Array.each(a_keys, function(i_record) {

				var a_columns = i_record.get("columns") || [];

				Ext.Array.each(a_columns, function(o_column) {
					if (o_column.name == originalName) {
						o_column.name = newName;
					}
				});

				i_record.commit();
			});

			var i_storeRelation = i_relationManager.relationGrid.store;
			var a_relations = i_storeRelation.getRange();

			Ext.Array.each(a_relations, function(i_record) {

				var s_between = i_record.get("betweenEntity");
				var s_and = i_record.get("andEntity");

				if (o_entity.name == s_between) {

					var a_betweenOn = i_record.get("betweenOn") || [];

					Ext.Array.each(a_betweenOn, function(o_value) {
						if (o_value.name == originalName) {
							o_value.name = newName;
						}
					});
				}

				if (o_entity.name == s_and) {

					var a_andOn = i_record.get("andOn") || [];

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

						if (o_value.name == originalName) {
							o_value.name = newName;
						}
					});
				}

				i_record.commit();
			});

			i_entityManager.fireEvent("updateColumn", originalName, newName);
		}
	},

	getCellEditor: function(i_record) {

		var i_self = this;
		var s_property = i_record.get(i_self.nameField);
		var val = i_record.get(i_self.valueField);
		var i_editor = i_self.getConfigProp(s_property, "editor");
		var type = i_self.getConfigProp(s_property, "type");
		var o_editors = i_self.editors;

		if (i_editor) {
			var i_el = i_editor.el;
			if (i_el && i_el.destroyed) {
				var i_field = i_editor.field;
				i_editor = Ext.clone(i_field.initialConfig);
			}
		}

		if (i_editor) {
			
			if (!(i_editor instanceof Ext.grid.CellEditor)) {
				if (!(i_editor instanceof Ext.form.field.Base)) {
					i_editor = Ext.ComponentManager.create(i_editor, "textfield");
				}
				i_editor = i_self.setConfigProp(s_property, "editor", new Ext.grid.CellEditor({
					field: i_editor
				}));
			}
		}
		else if (type) {
			switch (type) {
				case "date":
					i_editor = o_editors.date;
					break;
				case "number":
					i_editor = o_editors.number;
					break;
				case "boolean":
					i_editor = o_editors.boolean;
					break;
				default:
					i_editor = o_editors.string;
			}
		}
		else if (Ext.isDate(val)) {
			i_editor = o_editors.date;
		}
		else if (Ext.isNumber(val)) {
			i_editor = o_editors.number;
		}
		else if (Ext.isBoolean(val)) {
			i_editor = o_editors.boolean;
		}
		else {
			i_editor = o_editors.string;
		}

		if (i_editor.field.xtype == "combosql") {

			var s_table = i_self.record.get("table");
			var s_oldtable;
			var s_split;

			if (s_table) {

				s_split = s_table.split("/");
				s_table = s_split.pop();
				s_oldtable = i_editor.field.options.file;
				i_editor.field.options.file = s_table;

				if (i_editor.field.isLoaded && s_oldtable != s_table) {

					i_record.set({
						value: ""
					});

					var i_store = i_editor.field.getStore();
					i_store.load();
				}
			}
		}

		i_editor.editorId = s_property;
		i_editor.field.column = i_self.valueColumn;

		if (i_editor.field.xtype == "i18ntextfield") {

			i_editor.alignment = "tl";

			if (!i_editor.isChanged) {

				i_editor.isChanged = true;

				i_editor.onFocusLeave = (function(f_old) {

					return function() {

						var i_field = this.field;
						if (!i_field.isChanging) {
							f_old.apply(this, arguments);
						}
					};
				})(i_editor.onFocusLeave);
			}
		}

		if (i_editor.field.xtype == "i18n-textfield") {
			i_editor.onFocusLeave = (function(f_old) {

				return function() {

					var i_field = this.field;
					var i_selection = i_field.getSelections();
					if (i_selection.isHidden()) {
						f_old.apply(this, arguments);
					}
				};
			})(i_editor.onFocusLeave);
		}

		if (s_property === "name") {

			//i_editor.field.fieldStyle = "text-transform:uppercase";

			i_editor.field.getValue = function() {

				var i_field = this;
				var value = i_field.rawToValue(i_field.processRawValue(i_field.getRawValue()));
				value = value;
				i_field.value = value;
				return value;
			};
		}
		return i_editor;
	}
});
