class UserRolesMappingServiceImpl implements UserRolesMappingService {

	@Override
	public String allocateUserRole(final UserRoleConfigRequest userRoleConfigRequest, final String allocator) throws PacManException {
		List<UserRolesMapping> allDeletedUserRoleAllocations = Lists.newArrayList();
		try {
			Date currentDate = new Date();
			List<UserRolesMapping> userRolesMappings = Lists.newArrayList();
			allDeletedUserRoleAllocations = userRolesMappingRepository.deleteByRoleId(userRoleConfigRequest.getRoleId());
			for(User user: userRoleConfigRequest.getUserDetails()) {
				if(userRolesRepository.existsById(userRoleConfigRequest.getRoleId())) {
					UserRolesMapping userRolesMapping = new UserRolesMapping();
					userRolesMapping.setAllocator(allocator);
					userRolesMapping.setClientId(oauth2ClientId);
					userRolesMapping.setCreatedDate(currentDate);
					userRolesMapping.setModifiedDate(currentDate);
					userRolesMapping.setRoleId(userRoleConfigRequest.getRoleId());
					userRolesMapping.setUserId(user.getUserId().toLowerCase());
					userRolesMapping.setUserRoleId(UUID.randomUUID().toString());
					userRolesMappings.add(userRolesMapping);
				}
			}
			if(!userRolesMappings.isEmpty()) {
				userRolesMappingRepository.saveAll(userRolesMappings);
			}
			return USER_ROLE_ALLOCATION_SUCCESS;
		} catch (Exception exception) {
			allDeletedUserRoleAllocations.parallelStream().forEach(userRolesMapping -> {
				userRolesMappingRepository.save(userRolesMapping);
			});
			throw new PacManException(USER_ROLE_ALLOCATION_FAILURE);
		}
	}

}