var angular = require('cla_angular');
var template = require('./html/rights.html');
require('cla_select2');

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

	var moduleName = 'cla.core.acl.rolebased'; var module;
	try { module = angular.module(moduleName); }
	catch(err) { module = angular.module(moduleName, ['cla.core.lmsg']); }
	// dependencies
	module.directive('claRightsList', claRightsList);

	claRightsList.$inject = ['$timeout'];
	function claRightsList($timeout) {
		var directive = {
			controller: controller,
			controllerAs: 'rights_list',
			replace: false,
			restrict: 'E',
			scope: {
				rights: '=',
				rightGroups: '='
			},
			templateUrl: template

		};
		directive.controller.$inject = ['$scope', 'claRoleService'];

		return directive;
		//////////////////

		/** directive controller */
		function controller($scope, roleService)
		{
			var ctrl = this;

            this.$onInit = function() {
                ctrl.rights = $scope.rights;
                ctrl.rightGroups = $scope.rightGroups;
                ctrl.displayRights = [];
                ctrl.roles = [];

                for (var i = 0; i < ctrl.rightGroups.length; i++)
                {
                    ctrl.rightGroups[i].rights.unshift(0);
                }

                // Build list of individual grouped rights to exclude from the list
                var groupedRights = [];
                for (i = 0; i < ctrl.rightGroups.length; i++)
                {
                    for (var j = 0; j < ctrl.rightGroups[i].rights.length; j++)
                    {
                        groupedRights.push(ctrl.rightGroups[i].rights[j]);
                    }
                }

                // Build list of individual rights to show
                for (i = 0; i < ctrl.rights.length; i++)
                {
                    if (groupedRights.indexOf(ctrl.rights[i].bitmask) === -1)
                        ctrl.displayRights.push(ctrl.rights[i]);
                }

                roleService.subscribeToRoleUpdates(function(roles)
                {
                    ctrl.roles = roles;

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

                    // When used in a different angular instance this needs to be done because the change in
                    // the roles DOM would not have triggered a digest in this one.
                    $timeout(function(){
                        $scope.$digest();
                    }, 0);
                });
            };

			ctrl.setRoleCheckboxState = function(role)
			{
				var count = 0;
				for (var i = 0; i < ctrl.rights.length; i++)
				{
					if ((role.rights & ctrl.rights[i].bitmask) === ctrl.rights[i].bitmask)
						count++
				}

				role.checked = (count === ctrl.rights.length);
			};

			ctrl.isRoleSelected = function(rightsValue, rightBitmask)
			{
				return (rightsValue & rightBitmask) === rightBitmask;
			};

			ctrl.getBitmaskForRole = function(role_id)
			{
				var roleBitmask = 0;
				for (var i = 0; i < ctrl.roles.length; i++)
				{
					if (ctrl.roles[i].id === role_id)
						roleBitmask = ctrl.roles[i].bitmask;
				}

				return roleBitmask;
			};

			ctrl.getRightName = function(bitmask)
			{
				if (bitmask === 0)
					return lmsg('acl.role_based.right_group.none');

				for (var i = 0; i < ctrl.rights.length; i++)
				{
					if (ctrl.rights[i].bitmask === bitmask)
					{
						return ctrl.rights[i].name;
					}
				}

				return lmsg('acl.role_based.right_group.unknown');
			};

			ctrl.getCurrentGroupValue = function(role, rights)
			{
				for (var i = 0; i < rights.length; i++)
				{
					if (rights[i] !== 0)
					{
						if ((role.rights & rights[i])  === rights[i])
							return rights[i];
					}
				}

				return 0;
			};

			ctrl.onRoleCheckboxChange = function(role)
			{
				var isChecked = role.checked;

				if (role.checked)
				{
					var allRights = 0;
					for (var i = 0; i < ctrl.rights.length; i++)
					{
						allRights = allRights | ctrl.rights[i].bitmask;
					}
					role.rights = allRights;
				} else
				{
					role.rights = 0;
				}

				roleService.setRights(role.id, role.rights);
			};

			ctrl.onRightCheckboxChange = function(role, bitmask)
			{
				var selected = ctrl.isRoleSelected(role.rights, bitmask);
				if (!selected)
					role.rights = (role.rights | bitmask);
				else
					role.rights = (role.rights & ~bitmask);

				roleService.setRights(role.id, role.rights);

				ctrl.setRoleCheckboxState(role);
			};

			ctrl.onRightGroupChange = function(role, rights, selectedRight)
			{
				for (var i = 0; i < rights.length; i++)
				{
					if ((rights[i] & role.rights) === rights[i])
						role.rights -= rights[i];
				}

				role.rights = role.rights | selectedRight;

				roleService.setRights(role.id, role.rights);
			};
        }
	}
}());
