package org.openur.module.domain.security.authorization;

import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.Validate;
import org.openur.module.domain.IdentifiableEntityBuilder;
import org.openur.module.domain.application.OpenURApplication;

public class OpenURRoleBuilder
	extends IdentifiableEntityBuilder<OpenURRoleBuilder>
{
	// properties:
	private String roleName = null;
	private String description = null;
	private Map<OpenURApplication, Set<OpenURPermission>> permissions = new HashMap<>();

	public OpenURRoleBuilder(String roleName)
	{
		super();

		Validate.notEmpty(roleName, "role-name must not be empty!");
		
		this.roleName = roleName;
	}
	
	// builder-methods:
	public OpenURRoleBuilder description(String description)
	{
		this.description = description;
		
		return this;
	}
	
	public OpenURRole build() 
	{
		return new OpenURRole(this);
	}
	
	public OpenURRoleBuilder permissions(Set<OpenURPermission> perms)
	{
		Map<OpenURApplication, Set<OpenURPermission>> permsLocal = new HashMap<>();
		
		for (OpenURPermission p : perms)
		{
			Set<OpenURPermission> sp = permsLocal.get(p.getApplication());
			
			if (sp == null)
			{
				sp = new HashSet<OpenURPermission>();
				permsLocal.put(p.getApplication(), sp);
			}

			sp.add(p);
		}
		
		// make permission-sets unmodifiable:
		for (OpenURApplication app : permsLocal.keySet())
		{
			this.permissions.put(app, Collections.unmodifiableSet(permsLocal.get(app)));
		}
		
		return this;
	}

	// accessors:
	String getRoleName()
	{
		return roleName;
	}

	String getDescription()
	{
		return description;
	}

	Map<OpenURApplication, Set<OpenURPermission>> getPermissions()
	{
		return permissions;
	}
}

@@ -128,23 +128,19 @@
 va.util.
-HashSet
+Map
 ;%0D%0Aimpor
@@ -143,35 +143,35 @@
 mport java.util.
-Map
+Set
 ;%0D%0Aimport java.u
@@ -174,19 +174,33 @@
 va.util.
-Set
+stream.Collectors
 ;%0D%0A%0D%0Aimp
@@ -1083,24 +1083,26 @@
 %3E perms)%0D%0A%09%7B
+%09%09
 %0D%0A%09%09Map%3COpen
@@ -1156,283 +1156,118 @@
 l = 
-new HashMap%3C%3E();%0D%0A%09%09%0D%0A%09%09for (OpenURPermission p : perms)%0D%0A%09%09%7B%0D%0A%09%09%09Set%3COpenURPermission%3E sp = permsLocal.get(p.getApplication());%0D%0A%09%09%09%0D%0A%09%09%09if (sp == null)%0D%0A%09%09%09%7B%0D%0A%09%09%09%09sp = new HashSet%3COpenURPermission%3E();%0D%0A%09%09%09%09permsLocal.put(p.getApplication(), sp);%0D%0A%09%09%09%7D%0D%0A%0D%0A%09%09%09sp.add(p);%0D%0A%09%09%7D
+perms%0D%0A%09%09%09.stream()%0D%0A%09%09%09.collect(Collectors.groupingBy(OpenURPermission::getApplication, Collectors.toSet()));
 %0D%0A%09%09

use aggregate-function to build the permissions-map in OpenURRole