var angular = require('cla_angular');

/**
 * A table of roles
 */
(function () {
	'use strict';

	var moduleName = 'cla.core.acl.rolebased'; var module;

	// Manual singleton to be shared between roles and rights components
	var instance = null;
	if (instance === null)
	{
		instance = new ClaRoleService();
	}

	angular.module(moduleName)
		.service('claRoleService', function()
		{
			return instance;
		});

	function ClaRoleService() {
		var service = this;

		service.roles = [];
		service.roleSubscribers = [];
		service.rightSubscribers = [];

		service.setRoles = function(roles)
		{
			service.roles = roles;

			for (var i = 0; i < service.roleSubscribers.length; i++)
			{
				service.roleSubscribers[i](service.roles);
			}
		};

		service.setRights = function(role_id, rightsValue)
		{
			for (var i = 0; i < service.rightSubscribers.length; i++)
			{
				service.rightSubscribers[i](role_id, rightsValue);
			}
		};

		service.subscribeToRoleUpdates = function(callback)
		{
			service.roleSubscribers.push(callback);
			callback(service.roles);
		};

		service.subscribeToRightUpdates = function(callback)
		{
			service.rightSubscribers.push(callback);
		};
	}
}());