Ext.define('Ext.ux.navigation.view.RolePermissionNavigationTree', {
	extend: 'Ext.tree.Panel',
	alias: ['widget.rolepermissionnavigationtree'],
	border: false,
	useArrows: true,
	rootVisible: false,
	controller: 'navigation.rolepermissionnavigationtree',
	permissions: null,
	viewModel: {
		type: "rolepermissiontree"
	},
	listeners: {
		checkchange: 'nodeCheckChange'
	},
	requires: [
		"Ext.ux.navigation.controller.RolePermissionNavigationTree"
	],
	initComponent: function() {

		var i_self = this;

		var i_viewModel = i_self.getViewModel();

		i_viewModel.set("record", i_self.record);
		i_viewModel.set("permissions", i_self.permissions);
		i_viewModel.set("roles", i_self.roles || false);

		delete i_self.record;
		delete i_self.permissions;
		delete i_self.roles;

		var i_store = Ext.create('Ext.data.TreeStore', {
			fields: [
				{ name: 'ID', type: 'auto' },
				{ name: 'text', type: 'auto' },
				{ name: 'url', type: 'string' },
				{ name: 'leaf', type: 'bool' },
				{ name: "disabled", type: "bool" }
			],
			idProperty: 'ID',
			proxy: {
				type: 'ajax',
				url: "/wsh-services/wshProxy.aspx"
			},
			autoLoad: true,
			listeners: {
				beforeload: function(store, operation) {

					var i_proxy = store.getProxy();
					var o_extraParams = i_proxy.getExtraParams();
					var i_node = operation.node;
					var s_node = "root";

					if (!i_node.isRoot()) {
						s_node = i_node.get("ID");
					}

					Ext.apply(o_extraParams, {
						action: "treeStore",
						entity: "WSHMNUET00",
						displayCheckbox: false,
						language: "da",
						displayRootNode: "false",
						dmd: "dmd/webshop.dmd",
						xpd: "xpd/menus.xpd",
						hasRootCid: true,
						idField: "MNUMNUTKN",
						parentidField: "MNUPNTTKN",
						propertiesField: "MNUPROP",
						node: s_node
					});

					delete operation.node;
				},
				load: function(store, a_records) {

					if (!i_viewModel.isDestroyed && i_viewModel.getRoot()) {
						var a_permissions = i_viewModel.get("permissions");

						Ext.Array.each(a_records, function(i_node) {
							i_node.set("checked", false);
							var s_text = ip2.i18n(i_node.get("title"));
							var b_expand = false;

							if (i_node.get("TITLE")) {
								s_text = ip2.i18n(i_node.get("TITLE"));
							}
							else {
								s_text = ip2.i18n(i_node.get("text"));
							}

							i_node.set("text", s_text);

							Ext.Array.each(a_permissions, function(n_id) {
								if (i_node.get("ID") == n_id) {
									i_node.set("checked", true);
									b_expand = true;
									return false;
								}
							});

							i_node.commit();

							if (b_expand && !i_node.isLeaf()) {
								i_node.expand();
							}
						});
					}
				}
			}
		});

		i_self.store = i_store;

		i_self.callParent();
		i_self.enableBubble("dirtychange");
	}
});
