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

	initComponent: function() {

		var i_self = this;

		var a_columns = [
			{
				xtype: 'treecolumn',
				text: ip2.i18n({
					da: "Applikation",
					en: "Application"
				}),
				flex: 1,
				sortable: false,
				dataIndex: 'text'
			},
			{
				text: ip2.i18n({
					da: "Url",
					en: "Url"
				}),
				flex: 1,
				sortable: false,
				dataIndex: 'url',
				renderer: function(value, i_meta, i_node) {
					return i_node.get("url") || "";
				}
			}
		];
		i_self.columns = a_columns;
		var controller = i_self.getController();
		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', {
			model: "Ext.ux.navigation.model.RolePermissionTree",
			autoLoad: true,
			listeners: {
				beforeload: function(store, operation) {

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

					var token = i_record.get(i_record.idProperty);
					if (a_roles) {
						token = a_roles;
					}

					Ext.apply(o_extraParams, {
						roletoken: token,
						action: "ip2NavProxy.listMenuNodes",
						tree: true
					});

					delete o_extraParams.registry;
				},
				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) {

							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);
							i_node.set("checked", false);

							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");
	}
});
