Ext.define("Ext.ux.navigation.controller.RolePermissionPanel", {
	extend: "Ext.app.ViewController",

	alias: "controller.navigation.rolepermissionpanel",

	doHandleType: function(i_button, f_callback) {

		var i_controller = this;
		var i_view = i_controller.getView();
		var i_viewModel = i_controller.getViewModel();

		var i_grid = i_viewModel.get("permissionGrid");
		var i_gridController = i_grid.getController();
		var i_store = i_grid.getStore();
		var o_options = i_grid.options;

		var i_record = i_viewModel.get("record");
		var n_oldID = i_viewModel.get("oldID");
		var s_key = i_viewModel.get("key") + ".userowselection";
		var b_userrow = false;

		var i_pnlFilter = i_viewModel.get("filter");
		var i_permissionGrid = i_viewModel.get("permissionGrid");

		if (i_pnlFilter && i_button.checked) {
			if (i_button.inputValue) {
				i_pnlFilter.disable();
			}
			else {
				i_pnlFilter.enable();
			}
		}

		if (i_button.checked) {
			b_userrow = i_button.inputValue;

			var o_option = {
				file: "NAVDTAACC"
			};

			var s_id = i_record.idProperty;

			var o_key = {};
			o_key[s_id] = i_record.get(i_record.idProperty);

			var o_store = {
				keyTpl: s_id + " = " + "$" + s_id,
				key: o_key,
				propertyColumn: "USRFILTER",
				entity: "NAVUSRET00"
			};

			i_view.setLoading(ip2.i18n({
				da: "Opdater...",
				en: "Updating...."
			}));
			Ext.registry.util.Service.setSingleValue(o_option, s_key, b_userrow, o_store, function() {
				o_options.userowselection = b_userrow;
				if (f_callback && Ext.isFunction(f_callback)) {
					f_callback();
				}
				else {
					i_gridController.getRecords(i_record, n_oldID, function(a_records) {
						i_view.setLoading(false);
						i_store.removeAll(true);
						i_store.loadRawData(a_records, false);
						i_store.originalRecords = i_store.getRange();
						i_store.fireEvent("datachanged", i_store, i_store.getRange());
					});
				}
			});
		}
	},

	InitializeFilterDragZone: function(item) {

		var i_controller = this;
		var i_view = i_controller.getView();
		var i_viewModel = i_controller.getViewModel();
		var i_panel = item;
		var i_toolbar = item.getFilterBar();

		i_toolbar.dragZone = Ext.create("Ext.dd.DragZone", i_toolbar.getEl(), {
			getDragData: function(e) {

				var sourceEl = e.getTarget(i_toolbar.itemSelector, 10);
				var d;
				if (sourceEl) {

					d = sourceEl.cloneNode(true);
					d.id = Ext.id();
					return (i_toolbar.dragData = {
						sourceEl: sourceEl,
						repairXY: Ext.fly(sourceEl).getXY(),
						ddel: d,
						where: i_toolbar.getWhere(),
						filters: i_toolbar.getFilterConfig(),
						key: i_viewModel.get("key")
					});
				}
			},
			getRepairXY: function() {
				return this.dragData.repairXY;
			}
		});
	},

	onTransferFilters: function(i_button) {

		var i_controller = this;
		var i_view = i_controller.getView();
		var i_viewModel = i_controller.getViewModel();
		var i_dropzone = i_viewModel.get("filter");
		var i_grid = i_viewModel.get("dbGrid");
		var i_record = i_viewModel.get("record");
		var n_oldID = i_viewModel.get("oldID");
		var i_filerBar = i_grid.getFilterBar();

		var o_data = {
			key: i_viewModel.get("key"),
			filters: i_filerBar.getFilterConfig(),
			where: i_filerBar.getWhere()
		};

		var a_filter = i_controller.createFilters(o_data.filters, o_data);

		i_controller.doFilterDrop(null, null, null, o_data, function() {

			i_dropzone.removeAll();
			i_dropzone.add(a_filter);
			var i_radio = i_view.down("#filterSelection");
			if (i_radio) {
				i_radio.setValue(true);
				var i_grid = i_viewModel.get("permissionGrid");
				var o_options = i_grid.options;
				var i_store = i_grid.getStore();
				o_options.where = o_data.where;
				i_controller.doHandleType(i_radio, function() {
					if (i_store) {
						i_view.setLoading(false);
						var i_gridController = i_grid.getController();
						i_gridController.getRecords(i_record, n_oldID, function(a_records) {
							i_store.removeAll();
							i_store.loadRawData(a_records, false);
							i_store.originalRecords = i_store.getRange();
						});
					}
				});
			};
		});
	},

	InitializeFilterDropZone: function(item) {

		var i_controller = this;
		var i_view = i_controller.getView();
		var i_viewModel = i_controller.getViewModel();
		var i_dropzone = item;

		item.dropzone = Ext.create("Ext.dd.DropZone", item.getEl(), {

			getTargetFromEvent: function(e) {
				return e.target;
			},

			onNodeOver: function(target, dd, e, data) {
				var i_proto = Ext.dd.DropZone.prototype;
				return i_proto.dropAllowed;
			},

			onNodeDrop: function(target, dd, e, data) {

				i_dropzone.removeAll();
				i_controller.doFilterDrop(target, dd, e, data, function() {
					var a_filters = i_controller.createFilters(data.filters, data);
					i_dropzone.add(a_filters);
					var i_radio = i_view.down("#filterSelection");

					if (i_radio) {
						i_radio.setValue(true);
						var i_grid = i_viewModel.get("permissionGrid");
						var i_record = i_viewModel.get("record");
						var n_oldID = i_viewModel.get("oldID");
						var o_options = i_grid.options;
						var i_store = i_grid.getStore();
						o_options.where = data.where;
						i_controller.doHandleType(i_radio, function() {
							if (i_store) {
								i_view.setLoading(false);
								var i_gridController = i_grid.getController();
								i_gridController.getRecords(i_record, n_oldID, function(a_records) {
									i_store.removeAll();
									i_store.loadRawData(a_records, false);
									i_store.originalRecords = i_store.getRange();
								});
							}
						});
					};
				});
				return true;
			}
		});
	},

	createFilters: function(a_configs, i_data) {

		var a_items = [];
		var i_controller = this;
		var i_view = i_controller.getView();
		var i_viewModel = i_controller.getViewModel();
		var o_values = i_data;

		Ext.Array.each(a_configs, function(o_config) {

			var a_values = o_config.fieldValues;
			var a_checkbox = o_config.checkboxes;
			var b_not = o_config.notValue || false;

			o_config.applyFn = function() {

				var o_data = {
					key: o_values.key,
					filters: i_controller.getFilterConfig(),
					where: i_controller.getWhere()
				};

				i_controller.doFilterDrop(null, null, null, o_data, function() {
					var i_radio = i_view.down("#filterSelection");
					if (i_radio) {
						i_radio.setValue(true);
						var i_grid = i_viewModel.get("permissionGrid");
						var i_record = i_viewModel.get("record");
						var n_oldID = i_viewModel.get("oldID");
						var o_options = i_grid.options;
						var i_store = i_grid.getStore();
						o_options.where = o_data.where;
						i_controller.doHandleType(i_radio, function() {
							if (i_store) {
								i_view.setLoading(false);
								var i_gridController = i_grid.getController();
								i_gridController.getRecords(i_record, n_oldID, function(a_records) {
									i_store.removeAll();
									i_store.loadRawData(a_records, false);
									i_store.originalRecords = i_store.getRange();
								});
							}
						});
					};
				});
			};

			o_config.removeFn = function(i_filter) {};

			/* REMOVE UNUSED PROPERTIES SO THEY DONT POLLUTE THE FILTER */
			delete o_config.checkboxes;
			delete o_config.fieldValues;
			delete o_config.notValue;

			var i_filter = Ext.ux.grid.filter.util.createFilter(o_config);
			i_filter.setNot(b_not);

			/* ADD PROPERTIES SO WE DONT LOSE THEM FOR FURTHER USAGES */
			o_config.checkboxes = a_checkbox;
			o_config.fieldValues = a_values;
			o_config.notValue = b_not;

			var o_filterConfig = i_filter.getConfig();
			var a_filtercheckboxs = o_filterConfig.checkboxes;
			var a_filterfields = o_filterConfig.fields;
			var n_index = 0;

			ip2.each(a_filtercheckboxs, function(o_checkbox) {
				var i_field = a_filterfields[n_index];
				var value = a_values[n_index];
				o_checkbox.setValue(a_checkbox[n_index]);
				if (i_field.fieldtype != "bt") {
					if (o_checkbox.dataType == "enum" || o_checkbox.dataType == "entity") {
						n_count++;
						var i_store = i_field.getStore();
						i_store.on({
							load: {
								fn: function(store, records) {
									i_field.setValue(value);
								}
							}
						});
					}
					else {
						i_field.setValue(value);
					}
				}
				else {
					var o_value = a_values[n_index];
					var a_items = i_field.items.items;
					var i_first = a_items[0];
					var i_second = a_items[1];
					i_first.setValue(o_value.first);
					i_second.setValue(o_value.second);
				}
				n_index++;
			});
			a_items.push(i_filter);
		});
		return a_items;
	},

	doFilterDrop: function(target, dd, e, data, f_callback) {

		var i_controller = this;
		var i_view = i_controller.getView();
		var i_viewModel = i_controller.getViewModel();
		var s_whereValue = data.where;
		var s_whereKey = data.key + ".where";
		var s_userFiltersKey = data.key + ".filters";
		var a_filters = data.filters;
		var i_record = i_viewModel.get("record");

		var o_option = {
			file: "NAVDTAACC"
		};

		var s_id = i_record.idProperty;

		var o_key = {};
		o_key[s_id] = i_record.get(i_record.idProperty);

		var o_store = {
			keyTpl: s_id + " = " + "$" + s_id,
			key: o_key,
			propertyColumn: "USRFILTER",
			entity: "NAVUSRET00"
		};

		Ext.registry.util.Service.setSingleValue(o_option, s_whereKey, s_whereValue, o_store, function() {
			Ext.registry.util.Service.setSingleValue(o_option, s_userFiltersKey, a_filters, o_store, function() {
				f_callback();
			});
		});
	},

	getWhere: function() {

		var i_controller = this;
		var a_filters = i_controller.getFilters();
		var s_where = "";
		var n_whereAdded = 0;

		ip2.each(a_filters, function(i_filter, n_index) {
			var s_value = i_filter.getValue();
			if (s_value) {
				if (n_whereAdded == 0) {
					s_where += s_value;
					n_whereAdded++;
				}
				else {
					s_where += " AND " + s_value;
				}
			}
		});
		return s_where;
	},

	getFilters: function() {

		var i_controller = this;
		var i_view = i_controller.getView();
		var i_viewModel = i_controller.getViewModel();
		var i_pnlFilter = i_viewModel.get("filter");
		var a_filters = [];
		if (i_pnlFilter) {
			a_filters = i_pnlFilter.query("splitbutton[isFilter=true]");
		}
		return a_filters;
	},

	getFilterConfig: function() {

		var i_controller = this;
		var a_filters = i_controller.getFilters();
		var a_configs = [];

		Ext.Array.each(a_filters, function(i_button) {
			var i_config = i_button.getConfig();
			var o_sortInfo = i_button.getSortInfo();
			var a_checkbox = [];
			var a_values = [];
			ip2.each(i_config.checkboxes, function(i_checkbox) {
				a_checkbox.push(i_checkbox.checked);
			});
			ip2.each(i_config.fields, function(i_field) {
				if (i_field.fieldtype != "bt") {
					var value = i_field.getValue() || "";
					a_values.push(value);
				}
				else {
					var a_items = i_field.items.items;
					var i_first = a_items[0];
					var i_second = a_items[1];
					var o_value = {
						first: i_first.getValue() || "",
						second: i_second.getValue() || ""
					};
					a_values.push(o_value);
				}
			});
			var o_config = {
				dataIndex: i_button.dataIndex,
				dataType: i_button.dataType,
				dataDateType: i_button.dataDateType || "",
				isString: i_button.isString || false,
				multiSelect: i_button.multiSelect || false,
				sortDirection: o_sortInfo.direction,
				overRuleable: false,
				dmd: i_button.dmd || "",
				checkboxes: a_checkbox,
				fieldValues: a_values,
				notValue: i_button.getNot(),
				text: i_button.text,
				values: i_button.values || []
			};
			a_configs.push(o_config);
		});
		return a_configs;
	},

	onValidateDrop: function(e, data, i_grid) {

		var i_proto = Ext.dd.DropZone.prototype;
		var i_store = i_grid.getStore();
		var a_items = i_store.data.items;
		var a_records = data.records;
		var b_allowed = true;
		var n_count = 0;

		Ext.Array.each(a_records, function(i_record) {
			Ext.Array.each(a_items, function(i_item) {

				var s_id = i_item.get(i_item.idProperty);
				var n_id = i_record.get(i_record.idProperty);

				delete i_item.data[i_item.idProperty];
				delete i_record.data[i_item.idProperty];

				if (ip2.isEqual(i_item.data, i_record.data)) {
					n_count++;
				}

				i_item.set(i_item.idProperty, s_id);
				i_record.set(i_record.idProperty, n_id);
			});
		});

		if (n_count && n_count == a_records.length) {
			b_allowed = false;
		}

		return b_allowed ? i_proto.dropAllowed : i_proto.dropNotAllowed;
	},

	onGridDrop: function(a_records, f_callback) {

		var i_controller = this;
		var i_view = i_controller.getView();
		var i_viewModel = i_controller.getViewModel();
		var s_key = i_viewModel.get("key");
		var i_record = i_viewModel.get("record");

		var o_option = {
			key: s_key,
			id: i_record.idProperty,
			idProperty: i_record.get(i_record.idProperty),
			action: "ip2UsrPerm.saveFilterData"
		};

		var i_radio = i_view.down("#rowSelection");
		if (i_radio) {
			i_radio.setValue(true);i_controller.doHandleType(i_radio, function() {
				Ext.registry.util.Service.setDataAccess(o_option, "save", a_records, function(o_result) {
					i_view.setLoading(false);
					f_callback(o_result);
				});
			});
		};
	},

	onRowsRemove: function(a_records, f_callback) {

		var i_controller = this;
		var i_view = i_controller.getView();
		var i_viewModel = i_controller.getViewModel();
		var s_key = i_viewModel.get("key");
		var i_record = i_viewModel.get("record");

		var o_option = {
			key: s_key,
			id: i_record.idProperty,
			idProperty: i_record.get(i_record.idProperty),
			action: "ip2UsrPerm.deleteFilterData"
		};

		Ext.registry.util.Service.setDataAccess(o_option, "delete", a_records, function(o_result) {
			f_callback(o_result);
		});
	},

	onRowItemMenu: function(i_grid, i_record, item, index, e) {

		var i_controller = this;
		var i_view = i_controller.getView();
		var i_viewModel = i_controller.getViewModel();
		var i_grid = i_viewModel.get("permissionGrid");
		var s_key = i_viewModel.get("key");
		var i_record = i_viewModel.get("record");
		var i_store = i_grid.getStore();

		var o_option = {
			key: s_key,
			id: i_record.idProperty,
			idProperty: i_record.get(i_record.idProperty),
			action: "ip2UsrPerm.deleteFilterData"
		};

		var i_selectionModel = i_grid.getSelectionModel();
		var a_coords = e.getXY();

		e.preventDefault();

		var menu = Ext.widget("menu", {
			allowOtherMenus: false,
			items: [
				{
					text: ip2.i18n({
						da: "Slet",
						en: "Delete"
					}),
					itemId: "itmDelete",
					iconCls: "ip2-icon-delete",
					handler: function () {
						var a_records = i_selectionModel.getSelection();
						i_store.remove(a_records);
					}
				}
			]
		});

		menu.showAt(a_coords[0], a_coords[1]);
	}

});
