Ext.define("Portfolio.registry.view.Main", {

	extend: "Ext.tree.Panel",

	alias: "widget.registry-main",

	options: null,

	useArrows: true,

	controller: "registry.view.main",

	listeners: {
		itemcontextmenu: {
			fn: "onItemMenu"
		},
		itemdblclick: {
			fn: "onEdit"
		}
	},
	viewConfig: {
		toggleOnDblClick: false
	},
	plugins: {
		ptype: "cellediting",
		clicksToEdit: 1,
		listeners: {
			beforeedit: {
				fn: function(i_editor, i_context) {

					var i_self = i_context.grid; // <--- THIS IS DUE TO Ext.grid.plugin.CellEditiong save its owner as "grid"
					var i_store = i_self.getStore();
					var i_proxy = i_store.getProxy();
					var o_store = i_proxy.dataStore;
					var o_options = i_self.options;
					var i_record = i_context.record;

					if (i_record.isRoot()) {
						return false;
					}

					var o_meta = i_record.get("meta");
					var o_properties = o_meta.properties;

					if (o_properties.type == "bool") {
						return false;
					}
				}
			},
			edit: {
				fn: function(i_editor, i_context) {

					var i_self = i_context.grid; // <--- THIS IS DUE TO Ext.grid.plugin.CellEditiong save its owner as "grid"
					var i_store = i_self.getStore();
					var i_proxy = i_store.getProxy();
					var o_store = i_proxy.dataStore;
					var o_options = i_self.options;
					var i_record = i_context.record;
					var i_field = i_editor.editors.items[0].field;
					var value = i_field.getSubmitValue ? i_field.getSubmitValue() : i_field.getValue();
					i_record.set("value", value);

					Ext.registry.util.Service.setSingleValue(o_options, i_record.get("key"), value, o_store, function() {});
					i_record.commit();
				}
			}
		},
		getEditor: function(record, column) {

			var me = this;
			var i_tree = me.cmp; // <--- THIS IS THE TREE
			var o_options = i_tree.options;
			var editor;
			var editors = me.editors;
			var editorId = column.getItemId();

			var editorOwner = me.grid.ownerLockable || me.grid;
			if (!editor) {
				editor = column.getEditor(record);
				if (!editor || !(ip2.isAccessible("app.sysreg.data.update")) ||
								ip2.isAccessible("app.sysreg.data.schema." + o_options.library + ".update") ||
								ip2.isAccessible("app.sysreg.data.schema." + o_options.library + ".table." + o_options.file + ".update")
				) {
					return false;
				}

				if (editor instanceof Ext.grid.CellEditor) {
					editor.floating = true;
				}
				else {
					editor = new Ext.grid.CellEditor({
						floating: true,
						editorId: editorId,
						field: editor
					});
				}

				editor.field.excludeForm = true;

				if (editor.ownerCt !== editorOwner) {
					editorOwner.add(editor);
					editor.on({
						scope: me,
						specialkey: me.onSpecialKey,
						complete: me.onEditComplete,
						canceledit: me.cancelEdit
					});
					column.on("removed", me.onColumnRemoved, me);
				}
				editors.add(editor);
			}
			if (column.isTreeColumn) {
				editor.isForTree = column.isTreeColumn;
				editor.addCls(Ext.baseCSSPrefix + "tree-cell-editor");
			}

			editor.setGrid(me.grid);

			editor.editingPlugin = me;
			editor.alignment = "tl";

			if (editor.field.xtype == "i18ntextfield" || editor.field.xtype == "i18ntextareafield") {
				if (!editor.isChanged) {
					editor.isChanged = true;
					editor.onFocusLeave = (function(f_old) {
						return function(e) {
							var i_self = this;
							var i_field = this.field;
							if (!i_field.isChanging) {
								f_old.apply(this, arguments);
							}
						};
					})(editor.onFocusLeave);
				}
			}
			return editor;
		}
	},

	alternateClassName: [
		"Ext.registry.view.Main"
	],

	requires: [
		"Portfolio.registry.controller.view.Main",
		"Portfolio.registry.tree.store.Registry",
		"Portfolio.registry.ui.schema.Open",
		"Portfolio.registry.ui.schema.Save",
		"Portfolio.registry.view.Copy",
		"Portfolio.registry.view.Move"
	],

	initComponent: function() {

		var i_self = this;
		var o_config = i_self.initialConfig;
		var o_options = o_config.options || {};

		i_self.store = i_self.createStore(o_options);
		i_self.columns = i_self.createColumns();
		i_self.callParent(arguments);

		var i_store = i_self.getStore();

		i_store.on({
			load: {
				fn: function(store, a_records) {
					var i_view = i_self.getView();
					i_view.refresh();
				}
			}
		});

		i_self.addDocked(i_self.createToolbar());

		return i_self;
	},

	createColumns: function() {

		var i_self = this;
		var i_store = i_self.getStore();
		var i_proxy = i_store.getProxy();
		var o_store = i_proxy.dataStore;
		var o_options = i_self.options;

		var a_columns = [
			{
				xtype: "treecolumn", //this is so we know which column will show the tree
				text: ip2.i18n({
					da: "Nøgle",
					en: "Key"
				}),
				flex: 1,
				sortable: false,
				dataIndex: "text"
			},
			{
				text: ip2.i18n({
					da: "Værdi",
					en: "Value"
				}),
				flex: 1,
				dataIndex: "value",
				sortable: false,
				getEditor: function(i_record, defaultField) {

					if (!i_record.isRoot() && !Ext.isArray(i_record.get("value"))) {
						var i_field;
						var o_meta = i_record.get("meta") || {
							properties: {},
							plugin: {
								src: ""
							}
						};
						i_field = Ext.registry.util.Service.getEditor(o_options, i_record.data, o_store);
						return i_field;
					}
				},
				renderer: function(value, i_meta, i_node) {

					var o_meta = i_node.get("meta") || {
						properties: {},
						plugin: {
							src: ""
						}
					};
					var o_plugin = o_meta.plugin;
					if (o_plugin.src) {
						var o_evaled;
						try {
							eval("o_evaled = " + o_plugin.src);
						}
						catch (err) {
							console.log("eval error check plugin if its valid");
							o_evaled = {};
						}
						if (o_evaled.xtype) {
							var i_pluginField = Ext.widget(o_evaled.xtype, o_evaled);
							if (i_pluginField.renderer) {
								value = i_pluginField.renderer(value);
							}
							if (o_evaled.xtype == "combosql") {

								i_pluginField.renderer = function(value) {
									var i_self = this;
									var o_options = {
										library: i_self.schema,
										file: i_self.table
									};

									var o_params = Ext.apply({}, {
										action: "searchRow",
										search: "",
										columns: i_self.columns,
										start: 0,
										limit: -1
									});
									if (o_params.where) {
										delete o_params.where;
									}
									if (i_self.where) {
										o_params.where = i_self.getWhereTemplate(o_options);
									}
									if (!i_self.isLoaded && value) {
										if (o_params.where) {
											o_params.where = " AND " + i_self.valueColumn + " like %" + value + "%";
										}
										else {
											if (i_self.valueColumn) {
												o_params.where = i_self.valueColumn + " = \"" + value + "\"";
											}
										}
									}

									var o_result = ip2.sajax.request({
										url: Portfolio.dynapp.util.Service.getPath(o_options),
										payload: o_params,
										method: "POST",
										asJson: true
									});

									if (o_result.rows.length > 0) {
										Ext.Array.each(o_result.rows, function(o_record) {
											if (o_record.value == value) {
												value = ip2.i18n(o_record.key);
											}
										});
									}
									return value;
								};
								value = i_pluginField.renderer(value);
							}
						}
						else if (o_evaled.renderer) {
							value = o_evaled.renderer(value);
						}
					}
					else {
						var f_renderer;
						if (o_meta.properties.type == "date" || o_meta.properties.type == "timestamp") {
							var s_format = Ext.util.Format.dateFormat;
							if (o_meta.properties.type != "date") {
								s_format = s_format + " H:i";
								value = Ext.Date.parse(value, ip2.date2dbDate.parseFormat);
							}
							f_renderer = Ext.util.Format.dateRenderer(s_format);
							value = f_renderer(value);
						}
						else {
							if (Ext.isObject(value)) {
								value = ip2.i18n(value);
							}
							if (Ext.isArray(value)) {
								value = JSON.stringify(value);
							}
						}
					}
					if (o_meta.properties.type == "bool") {
						var b_checked = false;
						if (Ext.isString(value)) {
							if (value === "1") {
								b_checked = true;
							}
						}
						else {
							if (value) {
								b_checked = true;
							}
						}
						var s_key = i_node.get("key") + ".bool";
						var a_split = s_key.split(".");
						s_key = a_split.join("-");

						value = "<input id= \"" + s_key + "\" type=\"checkbox\"" + (b_checked ? "checked=\"checked\"" : "") + ">";
						i_self.addInputHandler(s_key, i_node);
					}

					return value;
				}
			}
		];
		return a_columns;
	},

	addInputHandler: function(s_key, i_values) {

		var i_self = this;
		var i_store = i_self.getStore();
		var i_proxy = i_store.getProxy();
		var o_store = i_proxy.dataStore;
		var o_options = i_self.options;
		var i_record = i_values;

		setTimeout(function () {

			var i_el = Ext.get(s_key);

			if (i_el && !i_el.hasHandler) {

				i_el.on({
					click: {
						fn: function (o_event, i_self) {

							if (!(ip2.isAccessible("app.sysreg.data.update")) ||
								ip2.isAccessible("app.sysreg.data.schema." + o_options.library + ".update") ||
								ip2.isAccessible("app.sysreg.data.schema." + o_options.library + ".table." + o_options.file + ".update")) {
								i_self.checked = !i_self.checked;
								return false;
							}

							var value = 0;
							if (i_self.checked) {
								value = 1;
							}
							i_record.set("value", value);
							Ext.registry.util.Service.setSingleValue(o_options, i_record.get("key"), value, o_store, function() {});
							i_record.commit();
						}
					}
				});
				i_el.hasHandler = true;
			}
		}, 4);
	},

	createStore: function(o_options) {

		var i_self = this;
		var o_store = i_self.dataStore;
		var i_store = Ext.create("Portfolio.registry.tree.store.Registry", {
				options: o_options,
				dataStore: o_store,
				root: {
					text: ip2.i18n({
						da: "...",
						en: "..."
					}),
					id: "root",
					expanded: false,
					allowDrop: false,
					allowDrag: false,
					visible: true,
					loaded: o_options.library ? false : true
				}
			});
		return i_store;
	},

	createToolbar: function() {

		var i_self = this;
		var o_options = i_self.options;
		var a_items = [];
		if (ip2.isAccessible("app.sysreg.functions.open") ||
			ip2.isAccessible("app.sysreg.functions.save")
			) {
			var i_menu = i_self.createMenu();
			if (i_menu.items.length > 0) {
				a_items.push({
					xtype: "button",
					text: ip2.i18n({
						en: "File",
						da: "Fil"
					}),
					itemId: "menu-file",
					iconCls: "pf-edit",
					menu: i_self.createMenu()
				});
				a_items.push("-");
			}
		}

		var a_return = i_self.createLabels(o_options);

		if (a_return.length > 0) {
			a_items = a_items.concat(a_return);
		}

		var i_toolbar = Ext.widget("toolbar", {
			dock: "top",
			items: a_items
		});

		i_self._actionBar = i_toolbar;

		return i_toolbar;
	},

	createMenu: function() {

		var i_self = this;
		var o_options = i_self.options;
		var a_items = [];

		if (ip2.isAccessible("app.sysreg.functions.open")) {
			var i_open = Ext.widget("menuitem", {
				itemId: "menu-file",
				text: ip2.i18n({
					en: "Open",
					da: "Åben"
				}),
				handler: function() {
					var i_editor = Ext.widget("registry.ui.schema.open", {
						title: ip2.i18n({
							en: "Open",
							da: "Åben"
						}),
						width: 600
					});
					var i_viewmodel = i_editor.getViewModel();
					i_viewmodel.setData({
						tree: i_self
					});
					i_editor.show();
				}
			});

			a_items.push(i_open);
		}

		if (ip2.isAccessible("app.sysreg.functions.save")) {
			var i_save = Ext.widget("menuitem", {
				text: ip2.i18n({
					en: "Save as",
					da: "Gem som"
				}),
				itemId: "item-save",
				disabled: o_options.library == "" || o_options.file == "",
				handler: function(item) {
					var i_editor = Ext.widget("registry.ui.schema.save", {
						title: ip2.i18n({
							da: "Gem registry:",
							en: "Save registry:"
						}),
						width: 800,
						tree: i_self
					});
					i_editor.show();
				}
			});

			a_items.push(i_save);
		}

		var o_menu = {
			items: a_items
		};

		return o_menu;
	},

	createLabels: function(o_options) {

		var i_self = this;
		var a_items = [];
		if (o_options.library) {
			var o_item = {
				xtype: "tbtext",
				text: ip2.i18n({
					da: "Skema",
					en: "Schema"
				}) + ": " + o_options.library
			};

			a_items.push(o_item);
		}

		if (o_options.file) {
			var o_item = {
				xtype: "tbtext",
				text: ip2.i18n({
					da: "Tabel",
					en: "Table"
				}) + ": " + o_options.file
			};

			a_items.push(o_item);
		}

		return a_items;
	},

	getActionBar: function() {

		var i_self = this;
		return i_self._actionBar;
	},

	doUpdate: function(o_options) {

		var i_self = this;
		var i_actionBar = i_self.getActionBar();

		var a_items = i_actionBar.query("[xtype=tbtext]");
		Ext.Array.each(a_items, function(i_item) {
			i_actionBar.remove(i_item, true);
		});
		i_actionBar.insert(2, i_self.createLabels(o_options));

		var i_filemenu = i_actionBar.down("#menu-file");

		if (i_filemenu) {
			var i_plugin = i_filemenu.down("#item-properties");
			var i_save = i_filemenu.down("#item-save");
			if (i_plugin) {
				if (o_options.library && o_options.file) {
					i_plugin.enable();
				}
				else {
					i_plugin.disable();
				}
			}
			if (i_save) {
				if (o_options.library && o_options.file) {
					i_save.enable();
				}
				else {
					i_save.disable();
				}
			}
		}
	}
});
