Ext.define("Portfolio.designer.ui.domainModelEntityPropertyManager", {

	extend: "Ext.form.Panel",

	alias: [
		"widget.ip2DomainModelEntityPropertyManager"
	],

	border: false,

	bodyPadding: 10,

	layout: {
		type: "border"
	},

	requires: [
		"Portfolio.designer.ui.domainModelEntityColumnComboBox",
		"Portfolio.designer.model.domainModelEntityColumnManagerDataModel",
		"Portfolio.designer.ui.domainModelEntityHierarchyManager"
	],

	config: {
		hierarchyManager: null,
		entityManager: null,
		designer: null,
		entity: null,
		required: false
	},

	initComponent: function() {

		var i_self = this;
		var i_entityManager = i_self.getEntityManager();
		var b_newEntity = i_entityManager.getNewEntity();
		var o_entity = i_self.getEntity();
		var i_designer = i_self.getDesigner();

		var i_north = Ext.widget("panel", {
			region: "north",
			border: false,
			defaults: {
				xtype: "textfield",
				labelAlign: "left",
				labelWidth: 150,
				anchor: "100%"
			},
			layout: {
				type: "anchor"
			},
			items: [
				{
					fieldLabel: ip2.i18n({
						da: "Navn",
						en: "Name"
					}),
					name: "name",
					isInvalid: (b_newEntity) ? true : false,
					value: o_entity.name,
					readOnly: (b_newEntity) ? false : true,
					listeners: {
						change: {
							fn: function(field) {

								if (b_newEntity) {

									var s_value = field.getValue();

									Ext.Ajax.request({
										url: i_designer.serviceProxy + "?" + Ext.Object.toQueryString({
											action: "checkTable",
											lib: i_designer.model.name,
											tbl: s_value
										}),
										success: function (response) {

											var o_result = Ext.decode(response.responseText, true) || {
												success: false,
												msg: "Errror"
											};
											if (o_result.success) {
												field.markInvalid(ip2.i18n("tableAlreadyExists"));
											}

											var i_formDesigner = i_entityManager.getFormDesigner();

											if (i_formDesigner) {
												var i_form = i_self.getForm();
												var o_values = i_form.getFieldValues();
												i_formDesigner.fireEvent("entityChange", i_formDesigner, o_values);
											}
										}
									});
								}
							},
							scope: this,
							buffer: 500
						}
					}
				},
				{
					fieldLabel: ip2.i18n({
						da: "System Object Name",
						en: "System Object Name"
					}),
					name: "sysname",
					value: o_entity.sysname || "",
					readOnly: (b_newEntity || !o_entity.sysname) ? false : true,
				},
				{
					xtype: "i18n-textfield",
					fieldLabel: ip2.i18n({
						da: "Titel",
						en: "Titel"
					}),
					name: "title",
					value: o_entity.title,
					asJSON: true,
					model: i_designer.model,
					allowBlank: false,
					listeners: {
						change: {
							fn: function(field, newValue, oldValue) {

								var i_formDesigner = i_entityManager.getFormDesigner();
								if (i_formDesigner) {
									var i_form = i_self.getForm();
									var o_values = i_form.getFieldValues();
									i_formDesigner.fireEvent("entityChange", i_formDesigner, o_values);

									i_entityManager.setChanged(newValue);
								}
							},
							buffer: 500
						}
					}
				},
				{
					fieldLabel: ip2.i18n({
						da: "ID Kolonne",
						en: "ID Column"
					}),
					xtype: "ip2DomainModelEntityColumnComboBox",
					multiSelect: false,
					store: Ext.create("Ext.data.Store", {
						model: "Portfolio.designer.model.domainModelEntityColumnManagerDataModel"
					}),
					name: "idColumn",
					value: o_entity.idColumn,
					allowBlank: true,
					disabled: (!Ext.isEmpty(o_entity.primaryKey)) ? true : false,
					listeners: {
						afterender: {
							fn: function(i_field) {
								i_field.setValue(o_entity.idColumn || "");
							}
						},
						select: {
							fn: function(box, records) {
								if (Ext.isEmpty(records)) {
									i_self.getForm().findField("primaryKey").setDisabled(false);
								}
								else {
									i_self.getForm().findField("primaryKey").setDisabled(true);
								}
							}
						},
						blur: {
							fn: function(box) {
								if (Ext.isEmpty(box.getValue())) {
									i_self.getForm().findField("primaryKey").setDisabled(false);
								}
								else {
									i_self.getForm().findField("primaryKey").setDisabled(true);
								}
							}
						}
					}
				},
				{
					fieldLabel: ip2.i18n({
						da: "Primærnøgle",
						en: "Primary Key"
					}),
					xtype: "ip2DomainModelEntityColumnComboBox",
					multiSelect: true,
					store: Ext.create("Ext.data.Store", {
						model: "Portfolio.designer.model.domainModelEntityColumnManagerDataModel"
					}),
					name: "primaryKey",
					value: o_entity.primaryKey,
					allowBlank: true,
					disabled: (!Ext.isEmpty(o_entity.idColumn)) ? true : false,
					listeners: {
						afterender: {
							fn: function(i_field) {
								i_field.setValue(o_entity.primaryKey || "");
							}
						},
						select: {
							fn: function(box, records) {
								if (Ext.isEmpty(records)) {
									i_self.getForm().findField("idColumn").setDisabled(false);
								}
								else {
									i_self.getForm().findField("idColumn").setDisabled(true);
								}
							}
						},
						blur: {
							fn: function(box) {
								if (Ext.isEmpty(box.getValue())) {
									i_self.getForm().findField("idColumn").setDisabled(false);
								}
								else {
									i_self.getForm().findField("idColumn").setDisabled(true);
								}
							}
						}
					}
				},
				{
					xtype: "textfield",
					fieldLabel: ip2.i18n({
						da: "Hook",
						en: "Hook"
					}),
					name: "hook",
					value: o_entity.hook,
					allowBlank: true
				},
				{
					xtype: "textfield",
					fieldLabel: ip2.i18n({
						da: "DB2 Filnavn",
						en: "DB2 Filename"
					}),
					name: "file",
					value: o_entity.file,
					allowBlank: true
				}
			]
		});

		var i_hierarchy = Ext.create("Portfolio.designer.ui.domainModelEntityHierarchyManager", {
			flex: 1,
			split: true,
			designer: i_designer,
			entityManager: i_entityManager,
			entity: o_entity,
			required: i_self.getRequired()
		});

		var i_editorArea = Ext.widget("panel", {
			flex: 1,
			split: true,
			layout: {
				type: "vbox",
				align: "stretch"
			},
			bodyPadding: 10,
			defaults: {
				xtype: "fieldset",
				collapsible: true,
				flex: 1
			},
			items: [
				{
					title: "Pre DDL",
					layout: "fit",
					items: [
						{
							xtype: "acetextarea",
							name: "preddl",
							useWorker: false,
							mode: "sql",
							asArray: true,
							splitRegEx: /;$/gm,
							joinDelimiter: "",
							value: o_entity.preddl
						}
					]
				},
				{
					title: "Post DDL",
					layout: "fit",
					items: [
						{
							xtype: "acetextarea",
							name: "postddl",
							addNewLine: false,
							useWorker: false,
							mode: "sql",
							asArray: true,
							splitRegEx: /;$/gm,
							joinDelimiter: "",
							value: o_entity.postddl
						}
					]

				}
			]
		});

		var i_center = Ext.widget("panel", {
			region: "center",
			border: false,
			flex: 1,
			layout: {
				type: "hbox",
				align: "stretch"
			},
			items: [
				i_hierarchy,
				i_editorArea
			]
		});

		i_self.items = [
			i_north,
			i_center
		];

		i_self.callParent();

		i_self.on({
			datachanged: {
				fn: function(a_records, i_selected) {

					var i_form = i_self.getForm();

					var i_idColumn = i_form.findField("idColumn");
					var i_primary = i_form.findField("primaryKey");

					var value;
					var i_store;

					var a_data = [];

					Ext.Array.each(a_records, function(i_record) {
						a_data.push(i_record.getData());
					});

					if (i_idColumn) {

						value = i_idColumn.getValue();
						i_store = i_idColumn.getStore();
						i_store.removeAll(true);
						i_store.loadRawData(a_data);

						if (!i_idColumn.isDisabled()) {

							if (i_selected && i_selected.id === value) {
								value = i_selected.get(i_idColumn.valueField);
							}
						}
						else {
							value = null;
						}
						i_idColumn.setValue(value);
					}

					if (i_primary) {

						value = i_primary.getValue();
						i_store = i_primary.getStore();
						i_store.removeAll(true);
						i_store.loadRawData(a_data);

						if (!i_primary.isDisabled()) {

							if (i_selected && i_selected.id === value) {
								value = i_selected.get(i_primary.valueField);
							}
						}

						else {
							value = null;
						}

						i_primary.setValue(value);
					}
				}
			}
		});

		var a_fields = i_self.getForm().getFields().items;

		Ext.Array.each(a_fields, function(i_field) {
			if (i_self.getRequired()) {
				i_field.setDisabled(true);
			}
		});

		i_self.setHierarchyManager(i_hierarchy);
	},

	doSave: function(o_entity) {

		var i_self = this;

		o_entity = o_entity || i_self.getEntity();

		var i_form = i_self.getForm();
		var i_hierarchyManager = i_self.getHierarchyManager();
		var idColumn = i_form.findField("idColumn").getRawValue();
		var primaryKey = i_form.findField("primaryKey").getRawValue();

		if (idColumn.length === 0 && primaryKey.length === 0) {

			ip2.messageBox({
				title: ip2.i18n("error"),
				message: Ext.String.format(ip2.i18n("selectEitherIDorKeyColumn"), ip2.i18n("idColumn"), ip2.i18n("primaryKey")),
			});

			return false;
		}

		if (!i_form.isValid()) {
			return false;
		}
		else {

			var i_field = i_form.findField("name");

			if (i_field.isInvalid) {
				i_field.markInvalid(ip2.i18n("tableAlreadyExists"));
				return false;
			}

			var o_values = i_form.getFieldValues();

			var a_pre = [];
			var a_post = [];

			var a_split = o_values.preddl || [];

			a_split = Ext.Array.filter(a_split, function(value) {
				return value;
			});

			Ext.Array.each(a_split, function(s_value) {
				if (s_value !== "\n") {
					s_value = s_value + ";";
				}

				a_pre.push(s_value);
			});

			o_values.preddl = a_pre;

			a_split = o_values.postddl || [];

			a_split = Ext.Array.filter(a_split, function(value) {
				return value;
			});

			Ext.Array.each(a_split, function(s_value) {
				if (s_value !== "\n") {
					s_value = s_value + ";";
				}
				a_post.push(s_value);
			});

			o_values.postddl = a_post;

			Ext.apply(o_entity, o_values);

			if (!primaryKey) {
				delete o_entity.primaryKey;
			}
			if (!idColumn) {
				delete o_entity.idColumn;
			}
			if (o_entity.preddl.length === 0) {
				delete o_entity.preddl;
			}
			if (o_entity.postddl.length === 0) {
				delete o_entity.postddl;
			}
		}

		// save hierachy (extend)

		var i_treeManager = i_hierarchyManager.getTreeManager();

		var i_root = i_treeManager.getRootNode();

		var o_extend = {};

		i_root.cascadeBy(function(i_record) {

			if (i_record.get("extend")) {
				o_extend.extend = i_record.get("extend");
				o_extend = o_extend.extend;
			}
		});

		if (Ext.Object.getKeys(o_extend).length > 0) {
			o_entity.extend = o_extend;
		}
		else {
			delete o_entity.extend;
		}

		return true;
	}
  });
