Ext.define("Ext.ux.folderorganizer.XpdEditor", {

	extend: "Ext.window.Window",

	action: "create",

	alias: "widget.xpd.editor.window",

	modal: true,

	collapsible: false,

	layout: {
		type: "fit"
	},

	idColumn: null,
	widgets: null,
	doSaveFields: null,

	config: {
		languageService: ""
	},

	tools: [
		{
			id: "link",
			cls: "pf-link",
			handler: function() {

				var i_tool = this;
				var i_xpdEditor = i_tool.up("window");
				var i_model = i_xpdEditor.record;

				i_model.widget = true;
				i_model.xpd = i_xpdEditor.xpd._name;
				i_model.dmdFile = i_xpdEditor.dmdFile;

				var i_window = Ext.widget("link.window", {
					model: i_model
				});

				i_window.show();
			},
			listeners: {
				afterrender: {
					fn: function(i_tool) {

						var i_image = i_tool.el.down("img");
						if (i_image) {
							i_image.setStyle("width", 0);
							i_image.setStyle("height", 0);
						}
					}
				}
			}
		}
	],

	requires: [
		"Ext.ux.container.Ip2Widget"
	],

	initComponent: function() {

		var i_cmp = this;
		var o_config = i_cmp.initialConfig;
		Ext.apply(i_cmp, {
			title: "",
			idColumn: o_config.idColumn || i_cmp.idColumn,
			action: o_config.action || i_cmp.action,
			constrain: true,
			width: 800,
			height: 600,
			collapsible: false,
			dmdFile: i_cmp.dmdFile || "dmd/webshop.dmd"
		});
		i_cmp.doSaveFields = [];
		i_cmp.widgets = [];

		i_cmp.callParent(arguments);

		var i_form = i_cmp.createFormConfig(i_cmp.action);

		i_cmp.add(i_form);

		i_cmp.preSave = i_cmp.preSave || function(a_modified, f_callback) {
			if (Ext.isFunction(f_callback)) {
				f_callback();
			}
		};

		return i_cmp;
	},

	createFormConfig: function (s_action) {

		var a_items = [];

		s_action = s_action || "update";

		var i_cmp = this;
		var o_config;

		var i_record = i_cmp.record;
		var s_prop = i_cmp.propertyNameMapping.PROPERTIES;

		// Since we do not have a real record when creating, we can not use get()
		var xpdValue = i_record.data[s_prop] || "{}";

		var i_xpdEditor = Ext.create("Ext.ux.xpd.Field", {
			xpd: i_cmp.xpd._name,
			value: xpdValue,
			environment: i_cmp.environment || "folderorganizer",
			action: s_action,
			record: i_cmp.record
		});

		i_cmp.on("xpdfieldadded", function(i_field) {
			if (i_field.doSave) {
				i_cmp.doSaveFields.push(i_field.id);
			}
		});

		var o_xpdValues = JSON.parse(xpdValue);
		var s_title = "";
		var s_lang = ip2.navigator.currentUser.usrlng || "da";

		if (i_cmp.action == "update") {
			o_xpdValues.title = o_xpdValues.title || { da: "", en: "" };
			o_xpdValues.name = o_xpdValues.name || { da: "", en: "" };
			s_title = ip2.i18n(o_xpdValues.title);
			if (!s_title) {
				s_title = ip2.i18n(o_xpdValues.name);
			}
		}
		else {
			var s_value = i_cmp.xpd.flatten.collections[o_xpdValues.__cid__].title;
			s_title = ip2.xpd.translate(i_cmp.xpd, s_value, s_lang);
		}

		i_cmp.title = ip2.i18n(i_cmp.getI18N(i_cmp.action)) + " - " + s_title + ": " + i_record.get(i_record.idProperty);

		i_cmp.xpdEditor = i_xpdEditor;

		var i_content = Ext.widget("panel", {
			itemId: "content",
			title: ip2.i18n({
				da: "Indhold",
				en: "Content"
			}),
			layout: "fit",
			bodyPadding: 15,
			items: [i_xpdEditor]
		});

		a_items.push(i_content);

		var i_tabpanel = Ext.widget("tabpanel", {
			layout: "fit",
			defaults: {
				iconAlign: "right",
			},
			items: a_items,
			border: false
		});

		var i_form = Ext.widget("form", {
			layout: "fit",
			itemId: "contentForm",
			items: [i_tabpanel],
			trackResetOnLoad: true,
			buttons: [
				{
					xtype: "button",
					text: ip2.i18n({
						da: "Annuller",
						en: "Cancel"
					}),
					itemId: "close",
					handler: function () {
						i_cmp.close();
					}
				},
				{
					xtype: "button",
					text: ip2.i18n({
						da: "Gem",
						en: "Save"
					}),
					hidden: true,
					itemId: "save",
					ui: "primary-button",
					handler: function() {
						var msg = ip2.i18n({
							da: "Gemmer",
							en: "Saving"
						});
						i_cmp.setLoading(msg);
						i_cmp._doSave(function() {
							var a_dirty = [];
							ip2.each(i_cmp.xpdEditor.xpdComponent.xpdFields, function(i_field) {
								if (i_field.isDirty()) {
									a_dirty.push({
										name: i_field.name,
										value: i_field.value
									});
								}
							});
							i_cmp.preSave(a_dirty, function() {
								i_cmp.doSave(i_cmp.record, i_cmp.node, i_cmp.xpdEditor.getValue(), function(i_record, o_error) {
									if (i_record) {
										i_cmp.doLanguageService(i_cmp.record, function() {
											i_cmp.form.loadRecord(i_record);
											i_cmp._doSaveWidgets(function() {
												i_cmp.setLoading(false);
												i_cmp.close();
											});
										});
									}
									else {

										var s_msg = o_error.message;

										i_cmp.setLoading(false);

										ip2.messageBox({
											icon: Ext.MessageBox.ERROR,
											title: ip2.i18n({
												da: "Fejl",
												en: "Error"
											}),
											closable: true,
											message: ip2.i18n({
												da: "Der skete en fejl under processen: <strong>" + s_msg + "</strong>",
												en: "An error occurred durring the process: <strong>" + s_msg + "</strong>"
											}),
											yesText: ip2.i18n({
												da: "Ok",
												en: "OK"
											})
										});
									}
								});
							});
						});
					}
				}
			],
			listeners: {
				dirtychange: {
					fn: function(i_form, b_dirty) {

						var i_save = i_cmp.down("#save");
						var i_content = i_cmp.down("#content");
						var i_contentForm = i_cmp.down("#contentForm");

						var b_valid = i_form.isValid();

						if (b_valid) {
							b_dirty = i_contentForm.isDirty();

							i_save[b_dirty ? "show" : "hide"]();

							i_content.setIconCls(b_dirty ? "flatui icon-data-new" : "");
						}
					}
				},
				validitychange: {
					fn: function(i_form, b_valid) {

						var i_save = i_cmp.down("#save");
						var i_content = i_cmp.down("#content");
						var i_contentForm = i_cmp.down("#contentForm");

						if (!b_valid) {

							i_content.setIconCls("flatui icon-data-error");

							i_save[b_valid ? "hide" : "show"]();
						}
						else {
							var b_dirty = i_contentForm.isDirty();
							i_contentForm.fireEvent("dirtychange", i_contentForm, b_dirty);
						}
					}
				},
				afterrender: {
					fn: function (i_self) {

						var i_xpd = i_cmp.xpdEditor;

						i_xpd.resetOriginalValue();
					}
				}
			}
		});

		i_form.loadRecord(i_record);
		i_form.entity = i_cmp.entity || "";

		if (o_xpdValues.__cid__) {
			var o_collections = i_cmp.xpd.flatten.collections[o_xpdValues.__cid__];
			if (o_collections.widgets && Ext.isArray(o_collections.widgets)) {
				Ext.Array.each(o_collections.widgets, function(o_widget) {
					Ext.apply(o_widget, {
						widgetConfig: o_widget,
						_config: o_widget,
						title: ip2.i18n(o_widget.title),
						src: o_widget.path,
						border: false,
						dataParent: i_form,
						itemId: "widget_" + ip2.unique(),
						layout: "fit",
						index: o_widget.index || 0
					});
					var i_widget = Ext.widget("ip2widget", o_widget);
					if (i_widget.doSave) {
						i_cmp.widgets.push(i_widget.id);
					}
					i_tabpanel.add(i_widget);
				});
			}
		}
		i_cmp.form = i_form;

		return i_form;
	},

	getI18N: function(key) {
		return (ip2.folderorganizer) ? ip2.folderorganizer.getTextValue(key) : key;
	},

	doLanguageService: function(i_record, f_callback) {

		var i_self = this;
		if (i_self.getLanguageService()) {
			Ext.Ajax.request({
				url: i_self.getLanguageService(),
				jsonData: i_record.data,
				success: function(o_response) {

					var o_result = Ext.decode(o_response.responseText, true) || {
						success: false,
						message: "Could not parse response"
					};
					if (!o_result.success) {
						Ext.Error.handle({
							restart: false,
							message: {
								message: o_result.message
							},
							debug: "error",
							description: i_self.title +
							ip2.i18n({
								da: " fejl",
								en: " errror"
							})
						});
					}
					if (Ext.isFunction(f_callback)) {
						f_callback();
					}
				},
				failure: function(o_err) {

					var o_request = o_err.request;

					var s_message = [o_request.options.url, o_err.statusText]. join(": ");

					Ext.Error.handle({
						restart: false,
						message: {
							message: s_message
						},
						debug: "error",
						description: i_self.title +
						ip2.i18n({
							da: " fejl",
							en: " errror"
						})
					});
					if (Ext.isFunction(f_callback)) {
						f_callback();
					}
				}
			});
		}
		else {
			if (Ext.isFunction(f_callback)) {
				f_callback();
			}
		}
	},

	_doSave: function(f_callback) {

		var i_self = this;
		var n_ticker = 0;
		var a_fields = i_self.doSaveFields;

		if (a_fields.length > 0) {
			ip2.each(a_fields, function(s_field) {
				var i_field = Ext.getCmp(s_field);
				if (i_field) {
					n_ticker++;
					i_field.doSave(function() {
						n_ticker--;
						if (n_ticker == 0) {
							f_callback();
						}
					});
				}
			});
		}
		else {
			f_callback();
		}
	},
	_doSaveWidgets: function(f_callback) {

		var i_self = this;
		var n_ticker = 0;
		var a_widgets = i_self.widgets || [];

		if (a_widgets.length > 0) {
			Ext.Array.each(a_widgets, function(s_id) {
				var i_widget = Ext.getCmp(s_id);
				if (i_widget) {
					n_ticker++;
					i_widget.doSave(function() {
						n_ticker--;
						if (n_ticker == 0) {
							f_callback();
						}
					});
				}
			});
		}
		f_callback();
	}
});
