Ext.define("Ext.ux.navigation.view.RolePermissionTree", {

	extend: "Ext.tree.Panel",

	alias: [
		"widget.rolepermissiontree"
	],

	border: false,

	useArrows: true,

	rootVisible: false,

	serviceProgram: "/ip2-services/ip2NavProxy.aspx",

	controller: "navigation.rolepermissiontree",

	viewModel: {
		type: "rolepermissiontree"
	},

	listeners: {
		checkchange: "nodeCheckChange"
	},
	
	initComponent: function() {

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

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

		delete i_self.record;
		delete i_self.roles;
		delete i_self.registry;

		i_self.store = Ext.create("Ext.data.TreeStore", {
			model: "Ext.ux.navigation.model.RolePermissionTree",
			autoLoad: true,
			listeners: {
				beforeload: {
					fn: function(i_store, i_operation) {

						var i_record = i_viewModel.get("record");
						var a_roles = i_viewModel.get("roles");
						var s_registry = i_viewModel.get("registry");
						var i_proxy = i_store.getProxy();
						var o_extraParams = i_proxy.getExtraParams();

						var token = i_record.get(i_record.idProperty);

						if (a_roles) {
							token = a_roles;
						}

						Ext.apply(o_extraParams, {
							roletoken: token,
							action: "ip2NavProxy.listRolePermissionTree",
							registry: s_registry
						});
					}
				},
				load: {
					fn: function(i_store, a_records) {

						if (!i_self.isDestroyed) {

							Ext.Array.each(a_records, function(i_node) {

								var s_text = ip2.i18n(i_node.get("text"));
								i_node.set("text", s_text);
								i_node.commit();

								i_node.cascadeBy(function(i_child) {
									var s_text = ip2.i18n(i_child.get("text"));
									i_child.set("text", s_text);
									i_child.commit();
								});
							});

							i_self.removeIcon(a_records);

							i_controller.initializeRolePermissionGrid(i_store, a_records);
						}
					}
				}
			}
		});

		delete i_self.record;

		i_self.callParent();

		i_self.enableBubble("dirtychange");
	},

	removeIcon: function(a_nodes) {

		var i_self = this;

		Ext.Array.each(a_nodes, function(i_node) {

			var a_child = i_node.isModel ? i_node.get("children") || [] : i_node.children || [];
			var b_checked = i_node.isModel ? i_node.get("checked") : i_node.checked;

			if (a_child.length > 0) {
				i_self.removeIcon(a_child);
			}
			if (Ext.isDefined(b_checked)) {
				if (i_node.isModel) {
					i_node.set("iconCls", "x-tree-no-icon");
				}
				else {
					i_node.iconCls = "x-tree-no-icon";
				}
			}
		});
	}
});
