package com.gentics.mesh.core.data.generic;

import static com.gentics.mesh.core.data.perm.InternalPermission.READ_PERM;
import static org.apache.commons.lang3.StringUtils.isEmpty;

import java.util.Objects;
import java.util.Set;
import java.util.stream.Stream;

import javax.inject.Inject;
import javax.inject.Singleton;

import com.gentics.mesh.cli.BootstrapInitializer;
import com.gentics.mesh.context.InternalActionContext;
import com.gentics.mesh.core.data.HibBaseElement;
import com.gentics.mesh.core.data.dao.RoleDaoWrapper;
import com.gentics.mesh.core.data.perm.InternalPermission;
import com.gentics.mesh.core.data.role.HibRole;
import com.gentics.mesh.core.rest.common.PermissionInfo;
import com.gentics.mesh.core.result.Result;
import com.gentics.mesh.madl.traversal.TraversalResult;

@Singleton
public class PermissionProperties {

	private final BootstrapInitializer boot;

	@Inject
	public PermissionProperties(BootstrapInitializer boot) {
		this.boot = boot;
	}

	public Result<? extends HibRole> getRolesWithPerm(HibBaseElement element, InternalPermission perm) {
		RoleDaoWrapper roleDao = boot.roleDao();
		Set<String> roleUuids = roleDao.getRoleUuidsForPerm(element, perm);
		Stream<String> stream = roleUuids == null
			? Stream.empty()
			: roleUuids.stream();
		return new TraversalResult<>(stream
			.map(roleDao::findByUuid)
			.filter(Objects::nonNull));
	}

	public PermissionInfo getRolePermissions(HibBaseElement element, InternalActionContext ac, String roleUuid) {
		if (!isEmpty(roleUuid)) {
			RoleDaoWrapper roleDao = boot.roleDao();
			HibRole role = roleDao.loadObjectByUuid(ac, roleUuid, READ_PERM);
			if (role != null) {
				PermissionInfo permissionInfo = new PermissionInfo();
				Set<InternalPermission> permSet = roleDao.getPermissions(role, element);
				for (InternalPermission permission : permSet) {
					permissionInfo.set(permission.getRestPerm(), true);
				}
				permissionInfo.setOthers(false);
				return permissionInfo;
			}
		}
		return null;
	}
}

@@ -320,58 +320,8 @@
 n;%0A%0A
-import com.gentics.mesh.cli.BootstrapInitializer;%0A
 impo
@@ -740,16 +740,37 @@
 esult;%0A%0A
+import dagger.Lazy;%0A%0A
 @Singlet
@@ -828,33 +828,40 @@
 nal 
-BootstrapInitializer boot
+Lazy%3CRoleDaoWrapper%3E roleDaoLazy
 ;%0A%0A%09
@@ -901,55 +901,76 @@
 ies(
-BootstrapInitializer boot) %7B%0A%09%09this.boot = boot
+Lazy%3CRoleDaoWrapper%3E roleDaoLazy) %7B%0A%09%09this.roleDaoLazy = roleDaoLazy
 ;%0A%09%7D
@@ -1096,36 +1096,39 @@
 r roleDao = 
-boot.
 roleDao
+Lazy.get
 ();%0A%09%09Set%3CSt
@@ -1551,20 +1551,23 @@
 o = 
-boot.
 roleDao
+Lazy.get
 ();%0A

Refactor PermissionProperties to use roleDao directly