Ext.define("Ext.ux.help.view.Manager", {

	extend: "Ext.panel.Panel",
	alias: "widget.helpmanager",
	layout: "border",

	statics: {
		HELP_TEXT_CMP_ID: Ext.id(null, 'hlptxt-')
	},

	initComponent: function() {
		var i_self = this;
		i_self.callParent();
		i_self.add(i_self.createLayout());
		i_self.enableBubble("dirtychange");
		return i_self;
	},

	createLayout: function() {

		i_self = this;

		var a_items = [
			i_self.createWest(),
			i_self.createCenter()
		];

		return a_items;
	},

	createWest: function() {

		var i_self = this;
		var i_panel = Ext.widget("panel", {
			itemId: "helper-west",
			region: "west",
			width: 200,
			title: ip2.i18n({
				da: "Applikationer",
				en: "Applications"
			}),
			layout: "fit",
			items: [
				i_self.createTree()
			]
		});
		return i_panel;
	},

	createTree: function() {

		var i_self = this;
		var o_ns = ip2.resource.get("adm.ns", true);

		var i_tree = Ext.widget("treepanel", {
			useArrows: true,
			rootVisible: false,
			animate: false,
			listeners: {
				select: {
					fn: function(i_node, i_record) {
						if (i_record.get("leaf")) {
							var i_center = i_self.getCenter();
							i_center.setLoading(true);

							i_self.doSave(function(a_records) {
								var i_selected = i_record;
								var s_app = i_record.get("label").split(".").shift();

								i_self.getApplicationSteps(s_app, function(a_items) {
									Ext.Array.each(a_items, function(o_item) {
										if (o_item.label == i_selected.get("label")) {
											i_selected.set("helps", o_item.helps);
										}
									});

									var o_item = i_selected.data;
									var i_form = i_self.createUI(o_item);

									i_center.removeAll(true);
									i_center.add(i_form);
									i_center.setLoading(false);
									i_self.fireEvent("dirtychange", i_self, false);
								});
							});
						}
					}
				}
			}
		});

		var i_root = i_tree.getRootNode();

		i_self.getApplications(function(a_items) {

			i_root.appendChild(a_items);

			Ext.Array.each(a_items, function(o_item) {

				var i_item = o_item;

				i_self.getApplicationSteps(i_item.name, function(a_items) {
					var a_result = a_items;
					i_root.cascadeBy(function(i_node) {

						if (i_node.get("name") == i_item.name) {

							Ext.Array.each(a_result, function(o_result) {
								o_result.leaf = true;
								if (o_result.label) {
									var s_title = ip2.i18n(o_ns.getTextValue(o_result.label));
									if (!Ext.isString(s_title)) {
										s_title = "";
									}
									o_result.text = s_title;
								}
							});

							i_node.appendChild(a_result);
						}
					});
				});
			});
		});
		i_self.tree = i_tree;
		return i_tree;
	},

	createUI: function(o_item) {

		var i_self = this;
		var a_groups = [];
		var o_ns = ip2.resource.get("adm.ns", true);

		var a_fields = i_self.createFields(o_item.helps);
		var i_form = Ext.widget("form", {
			layout: "anchor",
			items: a_fields,
			bodyPadding: 5,
			autoScroll: true,
			buttons: [
				{
					text: "Gem",
					handler: function() {
						i_self.setLoading(true);
						i_self.doSave(function(a_records) {
							i_self.setLoading(false);
						});
					}
				}
			]
		});
		return i_form;
	},

	createFields: function(o_helps) {

		var i_self = this;

		var a_fields = [];
		var a_keys = Ext.Object.getKeys(o_helps);
		var o_xpd = ip2.resource.get("help.xpd", true);
		var o_ns = ip2.resource.get("adm.ns", true);

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

			var o_help = o_helps[s_key];
			var o_props = o_help.hlpprop || {};

			var a_xpdFields = Ext.ux.xpd.Handler.getFieldsWithValues(o_xpd, 1, o_props);
			Ext.Array.each(a_xpdFields, function(i_field) {
				i_field.propname = i_field.name;
				i_field.name = s_key + "." + i_field.name;
			});

			var s_title = ip2.i18n(o_ns.getTextValue(o_help.label));

			if (o_help.context) {
				var s_enumKey = 'helpContext';
				var i_resource = ip2.resource.get('adm.ns', true);
				var s_context = String(i_resource.getEnumValue(s_enumKey + '~' + o_help.context));

				// Enum value not defined / translated.
				if (!s_context) {
					s_context = o_help.context.replace(/^./, function(_) {
						return _;
					});
				}

				s_title += ' (' + s_context + ')';
			}

			var i_field = Ext.widget("fieldset", {
				name: s_key,
				title: s_title,
				collapsible: true,
				token: o_help.hlphlptkn != undefined ? o_help.hlphlptkn : 0,
				cmpid: Ext.getClass(i_self).HELP_TEXT_CMP_ID,
				prop: "HLPPROP",
				defaults: {
					margins: "0 5 0 0 "
				},
				layout: {
					type: "anchor"
				},
				items: a_xpdFields,
				getValue: function() {
					var i_fieldset = this;
					var a_fields = i_fieldset.items.items;
					var o_return = {};
					Ext.Array.each(a_fields, function(i_field) {
						var s_name = i_field.name.split(".").pop();
						var s_value = i_field.getValue();
						o_return[s_name] = s_value;
					});
					return o_return;
				}
			});

			a_fields.push(i_field);
		});

		return a_fields;
	},

	createCenter: function() {

		var i_self = this;

		var i_panel = Ext.widget("panel", {
			itemId: "helper-center",
			region: "center",
			title: ip2.i18n({
				da: "Hjælpetekster",
				en: "Help texts"
			}),
			layout: "fit"
		});

		return i_panel;
	},

	getApplications: function(f_callback) {

		var i_self = this;
		var o_ns = ip2.resource.get("adm.ns", true);

		Ext.Ajax.request({
			url: '/wsh-services/wshhelp.aspx',
			params: {
				action: "listapps"
			},
			success: function (response) {
				var result = {};
				result = JSON.parse(response.responseText);
				var a_items = result.items || [];
				Ext.Array.each(a_items, function(o_item) {
					var s_title = ip2.i18n(o_ns.getTextValue(o_item.label));
					if (!Ext.isString(s_title)) {
						s_title = "";
					}
					o_item.leaf = false;
					o_item.text = s_title;
				});
				f_callback(a_items);
			}
		});
	},

	getApplicationSteps: function(s_application, f_callback) {

		var i_self = this;

		Ext.Ajax.request({
			url: '/wsh-services/wshhelp.aspx',
			params: {
				action: "liststeps",
				app: s_application
			},
			success: function (response) {
				var result = {};
				result = JSON.parse(response.responseText);
				var a_items = result.items || [];
				f_callback(a_items);
			}
		});
	},

	getCenter: function() {
		var i_self = this;
		var i_center;
		if (i_self._centerpanel) {
			i_center = i_self._centerpanel;
		}
		else {
			var center = i_self.down("#helper-center");
			if (center) {
				i_self._centerpanel = center;
				i_center = center;
			}
		}
		return i_center;
	},

	doSave: function(f_callback) {

		var i_self = this;
		var a_fieldsets = i_self.query("[cmpid=" +
			Ext.getClass(i_self).HELP_TEXT_CMP_ID + "]");
		var a_records = [];
		Ext.Array.each(a_fieldsets, function(i_fieldset) {
			var n_token = i_fieldset.token;
			var s_prop = i_fieldset.prop;
			var o_value = i_fieldset.getValue();
			var i_record = i_self.getModel().create();
			i_record.set(i_record.idProperty, n_token);
			i_record.set("HLPID", i_fieldset.name);
			i_record.set(s_prop, JSON.stringify(o_value));
			a_records.push(i_record);
		});
		i_self.upsertRecords(a_records, f_callback);
	},

	getModel: function() {

		if (!i_self.model) {
			var f_model = ip2.model({
				dmd: "dmd/webshop.dmd",
				entityName: "WSHHLPET00",
				context: 'form',
				uiName: "portfolio"
			});
			i_self.model = f_model;
		}
		return i_self.model;
	},

	upsertRecords: function(a_records, f_callback) {
		var i_self = this;
		var a_batch = [];

		Ext.Array.each(a_records, function (i_record) {
			var key = {};
			key[i_record.idProperty] = i_record.get(i_record.idProperty);
			a_batch.push({
				type: 'upsert',
				dmd: 'dmd/webshop.dmd',
				entity: "WSHHLPET00",
				key: key,
				row: i_record.data
			});
		});

		Ext.Ajax.request({
			url: '/ip2-Services/ip2dmdproxy.aspx',
			jsonData: {
				transaction: {
					batch: a_batch
				}
			},
			success: function (o_response) {
				var o_result = JSON.parse(o_response.responseText);
				Ext.Array.each(o_result.batch, function(o_batch, n_index) {
					Ext.Array.each(o_batch.row, function(value) {
						a_records[n_index].set("HLPHLPTKN", value);
					});
				});
				f_callback(a_records);
			}
		});
	}
});
