Ext.define("Ext.ux.navigation.view.RolePermissionPanel", {
	extend: "Ext.panel.Panel",
	alias: ["widget.rolepermissionpanel"],
	controller: "navigation.rolepermissionpanel",
	requires: [
		"Ext.dynapp.view.Grid",
		"Ext.ux.navigation.controller.RolePermissionPanel",
		"Ext.ux.navigation.viewmodel.RolePermissionPanel",
		"Ext.ux.navigation.view.RolePermissionGrid",
		"Ext.ux.navigation.controller.RolePermissionGrid",
		"Ext.registry.util.Service"
	],
	record: null,
	layout: "border",
	viewModel: {
		type: "rolepermissionpanel"
	},

	initComponent: function() {

		var i_self = this;
		var i_viewModel = i_self.getViewModel();

		i_viewModel.set({
			record: i_self.record,
			key: i_self.key,
			oldID: i_self.oldID
		});

		delete i_self.record;
		delete i_self.key;
		delete i_self.oldID;

		i_self.callParent(arguments);
		i_self.createGrid();

		return i_self;
	},

	createGrid: function() {

		var i_self = this;
		var i_controller = i_self.getController();
		var i_viewModel = i_controller.getViewModel();

		if (i_self.options.dmd) {

			var i_grid = Ext.widget("ip2pagingGridOld", {
				region: "center",
				autoLoad: false,
				border: false,
				dmd: {
					path: i_self.options.dmd || "dmd/webshop.dmd",
					entityName: i_self.options.file
				},
				uiName: i_self.options.ui || "portfolio",
				key: i_viewModel.get("key"),
				flex: 1,
				selModel: Ext.create("Ext.selection.CheckboxModel", {
					enableKeyNav: true,
					pruneRemoved: false
				}),
				extraParams: i_self.options.extraParams,
				viewConfig: {
					trackOver: true,
					variableRowHeight: true,
					plugins: {
						ptype: "gridviewdragdrop",
						enableDrop: false,
						dragGroup: "grid2role"
					}
				},
				split: true,
				listeners: {
					afterrender: {
						fn: function(i_grid) {

							i_grid.events.itemdblclick.clearListeners();
							i_grid.events.itemcontextmenu.clearListeners();

							var i_actionBar = i_grid.getToolbar();
							var i_store = i_grid.getStore();

							var n_index = i_actionBar.removeExport();
							i_actionBar.items.removeAt(n_index);

							n_index = i_actionBar.removeAdd();
							i_actionBar.items.removeAt(n_index);

							var i_toolbar = i_grid.getFilterBar();

							var i_searchField = i_actionBar.getSearchField();

							if (i_searchField) {
								i_searchField.selectFn = function(i_record) {

									var i_view = i_controller.getView();
									i_view.doHandelAction([i_record]);
								};
							}

							i_grid.on({
								itemdblclick: {
									fn: function(i_gridview, i_record) {

										var i_view = i_controller.getView();
										i_view.doHandelAction([i_record]);
									}
								}
							});
							i_store.load();
						}
					}
				}
			});

			i_viewModel.set({
				dbGrid: i_grid
			});

			var i_west = i_self.createLayout();
			i_self.add(i_grid);
			i_self.add(i_west);
		}
		else {
			Ext.dynapp.util.Service.getMeta(i_self.options, function(o_metaData) {

				if (!i_self.isDestroyed) {
					if (o_metaData.fields.length > 0) {
						var o_properties = o_metaData.properties || {};
						o_properties = Ext.apply(o_properties, {
							plugin: {
								permissions: {
									create: false,
									read: false,
									update: false,
									delete: false
								}
							}
						});
						var o_options = Ext.apply(i_self.options, {
							properties: o_properties
						});
						var i_grid = Ext.widget("dynapp.gridpanel", {
							region: "center",
							options: o_options,
							fields: o_metaData.fields,
							idProperty: o_metaData.id,
							key: i_viewModel.get("key"),
							flex: 1,
							selModel: Ext.create("Ext.selection.CheckboxModel", {
								enableKeyNav: true,
								pruneRemoved: false
							}),
							viewConfig: {
								trackOver: true,
								variableRowHeight: true,
								plugins: {
									ptype: "gridviewdragdrop",
									enableDrop: false,
									dragGroup: "grid2role"
								}
							},
							split: true,
							autoLoad: false,
							border: false,
							listeners: {
								afterrender: {
									fn: function(i_grid) {

										i_controller.InitializeFilterDragZone(i_grid);

										i_grid.events.itemdblclick.clearListeners();
										i_grid.events.itemcontextmenu.clearListeners();

										var i_filterBar = i_grid.getFilterBar();
										var i_actionBar = i_grid.getActionBar();
										i_actionBar.removeAdd();
										if (ip2.isAccessible("app.portfolio.functions.navusret00.widgets.usertabelaccess.filters")) {
											i_filterBar.insert(0,
												{
													xtype: "button",
													iconCls: "pf-arrow_left",
													tooltip: ip2.i18n({
														da: "Brug dette filter",
														en: "Use this filter"
													}),
													reorderable: false,
													handler: function(i_button) {
														i_controller.onTransferFilters(i_button);
													}
												}
											);
											var i_separtor = Ext.widget("tbseparator", {
												reorderable: false
											});
											i_filterBar.insert(1,
												i_separtor
											);
										}
										i_grid.on({
											itemdblclick: {
												fn: function(i_gridview, i_record) {

													var i_view = i_controller.getView();
													i_view.doHandelAction([i_record]);
												}
											}
										});
									}
								}
							}
						});

						i_viewModel.set({
							dbGrid: i_grid
						});

						var i_west = i_self.createLayout();
						i_self.add(i_grid);
						i_self.add(i_west);
					}
				}
			});
		}
	},

	createLayout: function() {

		var i_self = this;

		var i_panel = Ext.widget("panel", {
			region: "west",
			layout: "border",
			flex: 1,
			split: true,
			border: false
		});

		i_self.createItems(function(a_items) {
			i_panel.add(a_items);
		});

		return i_panel;
	},

	createItems: function(f_callback) {

		var i_self = this;
		var i_controller = i_self.getController();
		var i_viewModel = i_controller.getViewModel();
		var i_selectionGrid = i_viewModel.get("dbGrid");

		var i_columnManager = i_selectionGrid.getColumnManager();
		var a_temp = i_columnManager.getColumns();
		var a_columns = [];

		Ext.Array.each(a_temp, function(i_column) {

			var o_config = Ext.clone(i_column.initialConfig);

			delete o_config.hide;

			a_columns.push(o_config);
		});

		var i_record = i_viewModel.get("record");
		var i_store = i_selectionGrid.getStore();
		var i_model = i_store.getModel();
		var a_fields = i_model.getFields();

		var o_option = {
			file: "NAVDTAACC"
		};

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

		Ext.registry.util.Service.getNode(o_option, { key: i_viewModel.get("key") },
			{
				keyTpl: s_id + " = " + "$" + s_id,
				key: o_key,
				propertyColumn: "USRFILTER",
				entity: "NAVUSRET00"
			},
			function(o_result) {

				if (i_self.isDestroyed) {
					return [];
				}

				var o_gridOptions = {
					record: i_record,
					key: i_viewModel.get("key"),
					userowselection: true,
					where: o_result.where
				};
				var a_items = [];
				var a_typeItems = [];
				var b_hideType = false;
				var b_hideFilter = false;

				if ((!ip2.isAccessible("app.portfolio.functions.navusret00.widgets.usertabelaccess.rows") ||
					!ip2.isAccessible("app.portfolio.functions.navusret00.widgets.usertabelaccess.filters"))) {
					if (ip2.isAccessible("app.portfolio.functions.navusret00.widgets.usertabelaccess.filters")) {
						o_result.userowselection = false;
					}
					else {
						o_result.userowselection = true;
					}
				}

				o_gridOptions.userowselection = true;

				var i_permissionGrid = Ext.widget("rolepermissiongrid", {
					region: "center",
					flex: 1,
					split: false,
					border: false,
					title: ip2.i18n({
						da: "Resultat",
						en: "Result"
					}),
					itemId: "rowGrid",
					columns: a_columns,
					fields : a_fields,
					options: o_gridOptions,
					selModel: Ext.create("Ext.selection.CheckboxModel", {
						enableKeyNav: true,
						pruneRemoved: false
					}),
					viewConfig: {
						plugins: {
							ptype: "gridviewdragdrop",
							enableDrop: true,
							enableDrag: false,
							dropGroup: "grid2role",
							dropZone: {
								notifyEnter: function(target, e, data) {

									var i_grid = i_viewModel.get("permissionGrid");
									var i_typepanel = i_viewModel.get("type");
									var s_status = "";
									var i_proto = Ext.dd.DropZone.prototype;

									if (i_typepanel.down("#rowSelection").getValue()) {
										s_status = i_controller.onValidateDrop(e, data, i_grid);
									}
									else {
										s_status = i_proto.dropNotAllowed;
									}
									return s_status;
								},
								notifyOver: function(target, e, data) {

									var i_grid = this.view.grid;
									var i_typepanel = i_viewModel.get("type");
									var i_proto = Ext.dd.DropZone.prototype;
									var s_status = i_proto.dropNotAllowed;

									if (i_typepanel.down("#rowSelection").getValue()) {
										s_status = i_controller.onValidateDrop(e, data, i_grid);
										if (i_proto.dropAllowed == s_status) {
											this.valid = true;
										}
									}
									else {
										s_status = i_proto.dropNotAllowed;
									}
									return s_status;
								}
							}
						},
						listeners: {
							beforedrop: {
								fn: function(node, data, overModel, dropPosition, dropHandler, e) {

									var a_records = [].concat(data.records);
									var i_view = i_controller.getView();

									data.records = [];
									data.copy = true;
									dropHandler.cancelDrop();

									i_view.doHandelAction(a_records);
								}
							}
						}
					},
					listeners: {
						added: {
							fn: function(i_grid) {
								var i_controller = i_grid.getController();
								var i_store = i_grid.getStore();
								i_controller.getRecords(i_record, i_viewModel.get("oldID"), function(a_records) {
									i_store.loadRawData(a_records);
									i_store.fireEvent("reset", i_store);
								});
							}
						},
						itemcontextmenu: {
							fn: function(i_grid, i_record, item, index, e) {

								e.preventDefault();
								var i_typepanel = i_viewModel.get("type");
								if (i_typepanel.down("#rowSelection").getValue()) {
									i_controller.onRowItemMenu(i_grid, i_record, item, index, e);
								}
							}
						}
					}
				});

				i_viewModel.set({
					permissionGrid: i_permissionGrid
				});

				a_typeItems.push({
					xtype: "radiofield",
					flex: 1,
					boxLabel: ip2.i18n({
						da: "Rækker",
						en: "Rows"
					}),
					name: "UserRowSelected",
					itemId: "rowSelection",
					isFormField: false,
					checked: true,
					inputValue: true,
					handler: "doHandleType"
				});

				a_typeItems.push({
					xtype: "radiofield",
					flex: 1,
					boxLabel: ip2.i18n({
						da: "Filter",
						en: "Filter"
					}),
					name: "UserRowSelected",
					itemId: "filterSelection",
					isFormField: false,
					inputValue: false,
					checked: false,
					handler: "doHandleType"
				});

				if (!ip2.isAccessible("app.portfolio.functions.navusret00.widgets.usertabelaccess.rows") ||
					!ip2.isAccessible("app.portfolio.functions.navusret00.widgets.usertabelaccess.filters")) {
					b_hideType = true;
				}

				var i_pnlType = Ext.widget("panel", {
					title: ip2.i18n({
						da: "Type",
						en: "Type"
					}),
					region: "west",
					width: 150,
					layout: {
						type: "vbox",
						align: "streach"
					},
					bodyPadding: 5,
					items: a_typeItems
				});

				i_viewModel.set({
					type: i_pnlType
				});

				a_items.push(i_pnlType);

				if (!ip2.isAccessible("app.portfolio.functions.navusret00.widgets.usertabelaccess.filters")) {
					b_hideFilter = true;
				}

				var i_pnlFilter = Ext.widget("panel", {
					title: "Filter",
					region: "center",
					itemId: "pnlFilter",
					flex: 1,
					bodyPadding: 10,
					layout: "hbox",
					disabled: true,
					defaults: {
						margin: "0 5 0 0"
					},
					items: [],
					listeners: {
						afterrender: {
							fn: "InitializeFilterDropZone"
						}
					}
				});

				a_items.push(i_pnlFilter);

				i_viewModel.set({
					filter: i_pnlFilter
				});

				var a_result = [
					{
						xtype: "panel",
						layout: "border",
						region: "north",
						itemId: "pnlType",
						height: 90,
						items: a_items,
						hidden: true
					},
					i_permissionGrid
				];
				f_callback(a_result);
			}
		);
	},

	doHandelAction: function(a_records) {

		var i_self = this;
		var i_controller = i_self.getController();
		var i_viewModel = i_controller.getViewModel();

		var i_grid = i_viewModel.get("permissionGrid");
		var i_store = i_grid.getStore();
		var i_model = i_store.getModel();

		var a_new = [];
		Ext.Array.each(a_records, function(i_record) {
			if (!i_store.findRecord(i_model.idProperty, i_record.get(i_record.idProperty))) {
				a_new.push(i_record);
			}
		});
		if (a_new.length > 0) {
			i_store.loadRawData(a_new, true);
		}
	}
});
