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

	alias: "controller.navigation.rolepermissiongrid",

	loadGridStoreFromTreeStore: function(a_checked) {
		var me = this;
		var view = me.getView();

		var a_rows = [];
		Ext.Array.each(a_checked, function(i_node) {
			var a_split = i_node.get("id").split(".");
			var s_group = "";
			if (a_split.length > 1) {
				s_group = a_split[1];
			}
			var o_data = {
				id: i_node.get("id"),
				description: i_node.get("text"),
				group: s_group
			};
			a_rows.push(o_data);
		});
		view.getStore().loadData(a_rows);
	},
	upsertRowFromTreeNode: function(node, checked) {
		var me = this;
		var view = me.getView();

		if (checked) {
			me.insertRowFromTreeNode(node);
		}
		else {
			me.removeRowFromTreeNode(node);
		}
	},
	insertRowFromTreeNode: function(i_node) {
		var me = this;
		var view = me.getView();

		var a_split = i_node.get("id").split(".");
		var s_group = "";
		if (a_split.length > 1) {
			s_group = a_split[1];
		}
		var o_data = {
			id: i_node.get("id"),
			description: i_node.get("text"),
			group: s_group
		};

		view.getStore().add(o_data);
	},
	removeRowFromTreeNode: function(node) {
		var me = this;
		var view = me.getView();

		var record = me.getRowByTreeNode(node);

		view.getStore().remove(record);
	},
	getRowByTreeNode: function(node) {
		var me = this;
		var view = me.getView();

		return view.getStore().getById(node.data.id);
	},

	getRecords: function(i_record, n_oldId, f_callback) {

		var i_controller = this;
		var i_view = i_controller.getView();
		var i_store = i_view.getStore();
		var i_viewModel = i_controller.getViewModel();
		var o_options = i_view.options;
		var b_rowselection = o_options.userowselection !== undefined ? o_options.userowselection : true;

		var o_apply = {
			action: "ip2UsrPerm.loadFilterData",
			access: o_options.key,
			userowselection: b_rowselection
		};
		o_apply[i_record.idProperty] = i_record.get(i_record.idProperty) || n_oldId;

		if (!b_rowselection) {
			Ext.apply(o_apply, {
				where: o_options.where
			});
		}

		Ext.Ajax.request({
			url: "/ip2-services/ip2transaction.aspx.json",
			method: 'POST',
			jsonData: o_apply,
			success: function(o_response) {

				if (o_response.responseText) {
					var o_result = JSON.parse(o_response.responseText);
					var a_rows = o_result.rows = o_result.rows || [];
					f_callback(a_rows);
				}
				else {
					f_callback([]);
				}
			}
		});
	}
});
