Ext.define("Portfolio.dynapp.view.Detail", {

	extend: "Ext.window.Window",

	alias: "widget.dynapp.detail",

	collapsible: true,

	viewModel: {
		type: "dynapp.detail"
	},

	controller: "dynapp.gridpanel",

	layout: "fit",

	constrain: true,

	props: [],

	uid: "",

	alternateClassName: [
		"Ext.dynapp.view.Detail"
	],

	requires: [
		"Portfolio.dynapp.controller.Grid",
		"Portfolio.dynapp.viewmodel.Detail"
	],

	initComponent: function() {

		var i_self = this;
		var o_options = i_self.options;
		var i_record = i_self.record;
		var i_model = i_self.model;
		var a_modelFields = i_self.grid.fields;
		i_self.callParent(arguments);

		var a_dataKeys = Ext.Object.getKeys(i_record.data);
		var a_extra = [];
		i_self.props = [];

		var i_boolStore = Ext.create("Ext.data.Store", {
			fields: [
				{ name: "key" },
				{ name: "value" }
			],
			data: [
				{ key: "false", value: 0 },
				{ key: "true", value: 1 }
			]
		});

		Ext.Array.each(a_dataKeys, function(s_key) {
			var s_field = s_key;
			var b_dont = false;
			Ext.Array.each(a_modelFields, function(i_modelField) {
				if (i_modelField.name == s_field) {
					if (i_modelField.plugin) {
						eval("o_plugin = " + i_modelField.plugin);
						if (o_plugin.xtype) {
							if (o_plugin.xtype.indexOf("i18n") != -1) {
								b_dont = true;
							}
						}
					}
				}
			});
			if (!b_dont) {
				var value = i_record.get(s_key);
				if (ip2.isStringedObject(value)) {
					value = Ext.decode(value);
				}
				if (Ext.isObject(value)) {
					var o_value = value;
					var a_keys = Ext.Object.getKeys(o_value);
					var a_fields = [];
					Ext.Array.each(a_keys, function(s_key) {

						var keyValue = o_value[s_key] || "";

						var o_field = {
							name: s_key,
							fieldLabel: s_key,
							propertyHost: s_field,
							readOnly: !(ip2.isAccessible("app.dynapp.data.update") ||
										ip2.isAccessible("app.dynapp.data.schema." + o_options.library + ".update") ||
										ip2.isAccessible("app.dynapp.data.schema." + o_options.library + ".table." + o_options.file + ".update")
										)
						};

						if (typeof keyValue == "number") {
							Ext.apply(o_field, {
								xtype: "numberfield",
								decimalSeparator: Ext.util.Format.decimalSeparator
							});
						}
						else if (keyValue instanceof Date) {
							Ext.apply(o_field, {
								xtype: "datefield",
								format: "d-m-Y",
								submitFormat: "Y-m-d"
							});
						}
						else if (typeof keyValue == "boolean") {

							Ext.apply(o_field, {
								xtype: "checkbox"
							});
						}
						else {
							if (Ext.isObject(keyValue) || Ext.isArray(keyValue)) {
								keyValue = Ext.encode(keyValue);
								Ext.apply(o_field, {
									xtype: "textarea",
									height: 150
								});
							}
							else {
								if (keyValue.length > 40) {
									Ext.apply(o_field, {
										xtype: "textarea"
									});
								}
								else {
									Ext.apply(o_field, {
										xtype: "textfield"
									});
								}
							}
						}

						a_fields.push(o_field);
						i_record.set(s_key, keyValue);
					});

					var s_title = "";

					Ext.Array.each(a_modelFields, function(i_modelField) {
						if (i_modelField.name == s_key) {
							s_title = i_modelField.header || i_modelField.name;
						}
					});

					var i_fieldset = Ext.widget("fieldset", {
						layout: "anchor",
						title: s_title,
						bodyPadding: 5,
						defaults: {
							anchor: "100%",
							labelWidth: 140
						},
						items: a_fields
					});

					if (i_self.props.indexOf(s_key) == -1) {
						i_self.props.push(s_key);
					}

					value = Ext.encode(value);
					i_record.set(s_key, value);
					a_extra.push(i_fieldset);
				}
			}
		});

		var i_form = i_self.createForm(i_model, i_record, a_extra);
		i_self.add(i_form);
		i_self._form = i_form;

		var i_viewModel = i_self.getViewModel();
		i_viewModel.setData({
			rec: i_record,
			grid: i_self.grid
		});

		i_form.loadRecord(i_record);

		return i_self;
	},

	createForm: function(i_model, i_record, a_extra) {

		var i_self = this;
		var i_form = Ext.widget("form", {
			layout: "border",
			region: "center",
			trackResetOnLoad: true,
			items: i_self.createItems(i_model, i_record, a_extra),
			buttons: i_self.createButtons()
		});

		i_form.on({
			dirtychange: {
				fn: function(i_form, b_dirty) {
					var i_button = i_form.owner.down("#btn-save");
					if (i_button) {
						if (!b_dirty) {
							i_button.disable();
						}
						else {
							i_button.enable();
						}
					}
				}
			},
			validitychange: {
				fn: function(i_form, b_valid) {
					var i_button = i_form.owner.down("#btn-save");
					if (i_button) {
						if (!b_valid) {
							i_button.disable();
						}
						else {
							var b_dirty = i_form.isDirty();
							if (b_dirty) {
								i_form.fireEvent("dirtychange", i_form, b_dirty);
							}
						}
					}
				}
			}
		});

		return i_form;
	},

	createItems: function(i_model, i_record, a_extra) {
		var i_self = this;
		var o_options = i_self.options;

		var a_items = [];

		var i_panel = Ext.widget("panel", {
			layout: "anchor",
			region: "center",
			bodyPadding: 5,
			flex: 1,
			trackResetOnLoad: true,
			autoScroll: true,
			defaults: {
				anchor: "100%"
			},
			items: i_self.createFields(i_model, i_record, a_extra)
		});

		a_items.push(i_panel);
		var i_tabpanel;
		if (o_options.properties.relations) {

			i_tabpanel = Ext.widget("tabpanel", {
				flex: 1,
				region: "south",
				split: true
			});

			i_tabpanel.add(i_self.createRelations(o_options, i_record));
		}
		if (o_options.properties.affiliations) {

			if (!i_tabpanel) {
				i_tabpanel = Ext.widget("tabpanel", {
					flex: 1,
					region: "south",
					split: true
				});
			}

			i_tabpanel.add(i_self.createAffiliations(o_options, i_record));
		}

		if (i_tabpanel) {
			a_items.push(i_tabpanel);
			i_tabpanel.setActiveTab(0);
		}
		return a_items;
	},

	createRelations: function(o_options, i_record) {

		var i_self = this;
		var o_relations = o_options.properties.relations;
		var a_items = [];

		Ext.Array.each(o_relations, function(o_relation) {
			var s_schema = o_options.library;
			var s_title = s_schema + " - " + o_relation.table;
			var s_itemId = s_schema + "-" + o_relation.table;
			var i_panel = Ext.widget("panel", {
				title: s_title,
				itemId: s_itemId,
				layout: "fit"
			});

			var o_values = {
				library: s_schema,
				file: o_relation.table
			};
			a_items.push(i_panel);

			Portfolio.dynapp.util.Service.getMeta(o_values, function(o_meta) {

				o_values.properties = o_meta.properties;

				var i_created = Ext.widget("dynapp.gridpanel", {
					fields: o_meta.fields,
					idProperty: o_meta.id,
					options: o_values,
					viewConfig: {
						trackOver: true,
						loadMask: true,
						variableRowHeight: true
					},
					numFromEdge: 4
				});

				var i_store = i_created.getStore();

				i_store.on({
					beforeload: {
						fn: function(store) {
							var i_proxy = store.getProxy();
							var o_extraParams = i_proxy.getExtraParams();
							var s_where = o_extraParams.where;
							var s_templateWhere = i_self.getWhere(o_relation, i_record);
							if (s_where) {
								s_where = s_where + " AND " + s_templateWhere;
							}
							else {
								s_where = s_templateWhere;
							}
							o_extraParams.where = s_where;
						}
					}
				});

				i_store.load();
				i_panel.add(i_created);
			});
		});
		return a_items;
	},

	createAffiliations: function(o_options, i_record) {

		var i_self = this;
		var o_affiliations = o_options.properties.affiliations;
		var a_items = [];

		Ext.Array.each(o_affiliations, function(o_affiliation) {

			var s_schema = o_options.library;
			var s_title = o_affiliation.name || o_options.library + " - " + o_options.file;

			var i_panel = Ext.widget("containeriframe", {
				title: s_title,
				src: i_self.getUrl(o_affiliation, i_record),
				layout: "fit"
			});

			a_items.push(i_panel);
		});
		return a_items;
	},

	createFields: function(i_model, i_record, a_extra) {

		var i_self = this;
		var o_options = i_self.options;

		if (i_record.store) {
			i_model = i_record.store.getModel();
		}

		var a_modelFields = i_self.grid.fields;

		var a_fields = [];

		Ext.Array.each(a_modelFields, function(i_modelField) {

			var i_field;
			var i_recordField = i_model.getField(i_modelField.name);

			if (!i_modelField.generated) {

				var o_config = {
					fieldLabel: i_modelField.header || i_modelField.name,
					name: i_modelField.name,
					hidden: i_modelField.hidden,
					bind: {
						value: "{rec." + i_modelField.name + "}"
					},
					isFormfield: true,
					defaultLanguage: ip2.getUser().get("USRLNG") || "en",
					languages: wsh.getLanguages("portfolio")
				};

				o_config.fieldLabel = ip2.i18n(o_config.fieldLabel);

				var s_type = "textfield";

				switch (i_modelField.datatype){
					case "string":
					case "char":
					case "varchar":

						if (i_modelField.size >= 40) {
							s_type = "textarea";
						}
						o_config = Ext.apply(o_config, {
							maxLength: i_modelField.size || 30
						});
						break;
					case "integer":
					case "int":
					case "decimal":
					case "dec":
					case "float":
						s_type = "numberfield";
						o_config = Ext.apply(o_config, {
							decimalPrecision: i_modelField.prec || 0,
							decimalSeparator: Ext.util.Format.decimalSeparator,
							maxLength: i_modelField.size || 30
						});
						break;
					case "timestamp":
						s_type = "isotimestampfield";
						break;
					case "date":
						s_type = "datefield";
						o_config = Ext.apply(o_config, {
							format: "d-m-Y",
							submitFormat: "Y-m-d"
						});
						break;
					case "time":
						s_type = "isotimestampfield";
						o_config = Ext.apply(o_config, {
							format: "d-m-Y",
							submitFormat: "Y-m-d",
							date: false,
							seconds: true
						});
						break;
					default :
						o_config = Ext.apply(o_config, {
							maxLength: i_modelField.size || 30
						});
						break;
				}

				var o_modelPlugin;
				var f_validator;
				if (i_recordField.plugin) {
					eval("o_modelPlugin = " + i_recordField.plugin);
					if (o_modelPlugin) {
						if (o_modelPlugin.xtype) {
							if (o_modelPlugin.xtype.indexOf("i18n") != -1) {
								var a_languages = o_config.languages;
								if (a_languages.indexOf(o_config.defaultLanguage) != 0) {
									var n_index = a_languages.indexOf(o_config.defaultLanguage);
									var s_value = a_languages.splice(n_index, 1)[0];
									a_languages.unshift(s_value);
								}
							}
							s_type = o_modelPlugin.xtype;
						}
						if (o_modelPlugin.validator) {
							f_validator = o_modelPlugin.validator;
							delete o_modelPlugin.validator;
						}
						Ext.apply(o_config, o_modelPlugin);
					}
				}

				if (i_recordField.identifier) {
					o_config.hidden = true;
				}

				if (i_self.props.indexOf(o_config.name) != -1) {
					o_config.hidden = true;
				}

				o_config.readOnly = !(ip2.isAccessible("app.dynapp.data.update") ||
										ip2.isAccessible("app.dynapp.data.schema." + o_options.library + ".update") ||
										ip2.isAccessible("app.dynapp.data.schema." + o_options.library + ".table." + o_options.file + ".update")
										);

				if (i_recordField.protected) {
					o_config.readOnly = i_recordField.protected;
				}

				try {
					i_field = Ext.widget(s_type, o_config);

					if (o_modelPlugin && f_validator) {
						i_field.getErrors = (function(f_old) {
							return function(value) {
								value = i_field.getValue();
								var a_errors = f_old.apply(this, [value]) || [];

								var s_error = f_validator.call(this, i_self._form.getForm(), value) || "";

								if (s_error) {
									a_errors.push(s_error);
								}

								return a_errors;
							};
						})(i_field.getErrors);
					}
					i_field.resetOriginalValue();
					a_fields.push(i_field);
				}
				catch (err) {}
			}
		});

		if (a_extra.length > 0) {
			Ext.Array.each(a_extra, function(i_fieldset) {
				a_fields.push(i_fieldset);
			});
		}

		return a_fields;
	},

	getWhere: function(o_relations, i_record) {

		var s_templete = o_relations.join;
		var tpl = Ext.create("Ext.XTemplate",
			"<tpl for=\".\">",
				s_templete,
			"</tpl>"
		);
		var div = document.createElement("div");
		i_template = tpl.compile();
		i_template.overwrite(div, i_record.data);
		var s_value = div.innerText;
		delete div;
		return s_value;
	},

	getUrl: function(o_relations, i_record) {

		var s_templete = o_relations.url;
		var regex = new RegExp("{","g");
		var regex_end = new RegExp("}","g");
		s_templete = s_templete.replace(regex, "{[this.encode(values.");
		s_templete = s_templete.replace(regex_end, ")]}");
		var tpl = Ext.create('Ext.XTemplate',
			"<tpl for=\".\">",
				s_templete,
			"</tpl>",
			{
				encode: function(value) {
					if (ip2.isStringedObject(value)) {
						value = Ext.decode(value);
					}
					if (Ext.isObject(value)) {
						value = ip2.i18n(value);
					}
					return encodeURIComponent(value);
				}
			}
		);
		var div = document.createElement("div");
		i_template = tpl.compile();
		i_template.overwrite(div, i_record.data);
		var s_value = div.innerText;
		delete div;
		return s_value;
	},

	createButtons: function() {

		var a_buttons = [
			{
				xtype: "button",
				text: "Save",
				itemId: "btn-save",
				handler: "onSave",
				disabled: true
			},
			{
				xtype: "button",
				text: "Close",
				itemId: "btn-close",
				handler: "onClose"
			}
		];
		return a_buttons;
	}
});
