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

/**
 * 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('claRoleList', claRoleList);

	function claRoleList() {
		var directive = {
			controller: controller,
			controllerAs: 'role_list',
			replace: false,
			restrict: 'E',
			scope: {
				roles: '=',
				options: '='
			},
			templateUrl: template

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

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


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

            this.$onInit = function() {
                ctrl.roles = $scope.roles;
                roleService.setRoles(ctrl.roles);
                ctrl.options = $scope.options;
                ctrl.perm_class = 142;
                ctrl.edit = {
                    curPerms: {owners: []}
                };
                ctrl.perms_control = {};

                // When adding new roles they will need a temporary id. This starts at 0 and will go downwards from there
                ctrl.nextId = 0;

                ctrl.resetEdit();

                ctrl.dragOptions = {
                    clone: true,
                    orderChanged: ctrl.updatePositions
                };

                roleService.subscribeToRightUpdates(function(role_id, rightsValue)
                {
                    for (var i = 0; i < ctrl.roles.length; i++)
                    {
                        if (ctrl.roles[i].id === role_id)
                            ctrl.roles[i].rights = rightsValue;
                    }

                    roleService.setRoles(ctrl.roles);

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

			ctrl.resetEdit = function()
			{
				ctrl.edit.index = -1;
				ctrl.edit.name = '';
				ctrl.edit.curPerms.owners = [];

				// Reset the perms picker
				if (ctrl.perms_control.populate !== undefined)
				    ctrl.perms_control.populate();
			};

			ctrl.onNewRole = function($event)
			{
				ctrl.resetEdit();
				angular.element('#editRole').modal('show');
			};

			ctrl.onEdit = function($event, role_id)
			{
				$event.preventDefault();
				ctrl.resetEdit();
                for (var i = 0; i < ctrl.roles.length; i++)
                {
                    if (ctrl.roles[i].id === role_id)
                    {
                        ctrl.edit.index = i;
                        ctrl.edit.name = ctrl.roles[i].name;
                        ctrl.edit.curPerms.owners = ctrl.roles[i].perms;
                    }
                }

                if (!ctrl.options.hide_picker)
                {
                    ctrl.perms_control.populate();
                }

				angular.element('#editRole').modal('show');
			};

			ctrl.onDelete = function($event, role_id)
			{
				$event.preventDefault();

				var index = -1;
				for (var i = 0; i < ctrl.roles.length; i++)
				{
					if (ctrl.roles[i].id === role_id)
						index = i;
				}

				if (index >= 0)
				{
					if (confirm('[Are you sure]'))
					{
						ctrl.roles.splice(index, 1);
						roleService.setRoles(ctrl.roles);
					}
				}
			};

			ctrl.onEditSubmit = function($event)
			{
				$event.preventDefault();

                if (!ctrl.options.hide_picker)
                {
                    ctrl.perms_control.sync();
                }

				if (ctrl.edit.index >= 0)
				{
					ctrl.roles[ctrl.edit.index].name = ctrl.edit.name;
					ctrl.roles[ctrl.edit.index].perms = ctrl.edit.curPerms.owners;
				} else
				{
					// Insert the new roles before any read only roles
					var index = 0;
					for (var i = 0; i < ctrl.roles.length && index === 0; i++)
					{
						if (ctrl.roles[i].read_only)
							index = i;
					}

					ctrl.roles.splice(index, 0, {
						id: ctrl.nextId--,
						position: -1,
						name: ctrl.edit.name,
						rights: 0,
						perms: ctrl.edit.curPerms.owners,
						read_only: false
					});
					ctrl.updatePositions();
				}

				roleService.setRoles(ctrl.roles);

				angular.element('#editRole').modal('hide');
			};

			ctrl.onEditCancel = function($event)
			{
				$event.preventDefault();
			};

			ctrl.updatePositions = function(data)
			{
				var position = 0;
				for (var i = 0; i < ctrl.roles.length; i++)
				{
					if (!ctrl.roles[i].read_only)
					{
						ctrl.roles[i].position = position;
						position++;
					}
				}
				for (i = 0; i < ctrl.roles.length; i++)
				{
					if (ctrl.roles[i].read_only)
					{
						ctrl.roles[i].position = position;
						position++;
					}
				}

				roleService.setRoles(ctrl.roles);
			};
		}
	}
}());
