package org.osiam.addons.administration.config;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.inject.Inject;

import org.osiam.addons.administration.model.session.GeneralSessionData;
import org.osiam.client.OsiamConnector;
import org.osiam.client.query.QueryBuilder;
import org.osiam.resources.scim.GroupRef;
import org.osiam.resources.scim.SCIMSearchResult;
import org.osiam.resources.scim.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

/**
 * This class is responsible for decide admin-access.
 */
@Component
public class AdminAccessDecisionManager implements AccessDecisionManager {

    @Inject
    private GeneralSessionData session;

    @Inject
    private OsiamConnector connector;

    @Value("${org.osiam.administration.adminGroups}")
    private String[] adminGroups;

    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) {
        // if there are no access-token in session
        if (session.getAccesstoken() == null) {
            throw new AccessDeniedException("There is no accesstoken in session!");
        }

        //groups.display eq "vr_bewerber" OR groups.display eq "vr_anwaerterStipendiat" OR groups.display eq "vr_stipendiat" OR groups.display eq "vr_anwaerterAltstipendiat"
//        List<GroupRef> userGroups = connector.getCurrentUser(session.getAccesstoken()).getGroups();

        StringBuilder queryString = new StringBuilder();
        queryString.append("userName eq ");
        queryString.append("\"");
        queryString.append(session.getAccesstoken().getUserName());
        queryString.append("\"");
        if (adminGroups.length > 0) {
            queryString.append(" AND ");
        }

        Iterator<String> groupIterator = Arrays.asList(adminGroups).iterator();
        while (groupIterator.hasNext()) {
            queryString.append("groups.display eq \"");
            queryString.append(groupIterator.next());
            queryString.append("\"");

            if(groupIterator.hasNext()) {
                queryString.append(" OR ");
            }
        }

        SCIMSearchResult<User> a = connector.searchUsers(new QueryBuilder().filter(queryString.toString()).build(), session.getAccesstoken());

        if(a.getTotalResults() != 1) {
            throw new AccessDeniedException("No permissions to user admin gui");
        }
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}

@@ -46,36 +46,8 @@
 g;%0A%0A
-import java.util.ArrayList;%0A
 impo
@@ -126,31 +126,8 @@
 tor;
-%0Aimport java.util.List;
 %0A%0Aim
@@ -266,16 +266,53 @@
 nector;%0A
+import org.osiam.client.query.Query;%0A
 import o
@@ -351,50 +351,8 @@
 er;%0A
-import org.osiam.resources.scim.GroupRef;%0A
 impo
@@ -1472,276 +1472,669 @@
     
-//groups.display eq %22vr_bewerber%22 OR groups.display eq %22vr_anwaerterStipendiat%22 OR groups.display eq %22vr_stipendiat%22 OR groups.display eq %22vr_anwaerterAltstipendiat%22%0A//        List%3CGroupRef%3E userGroups = connector.getCurrentUser(session.getAccesstoken()).getG
+checkForAdminGroup();%0A    %7D%0A%0A    private void checkForAdminGroup() %7B%0A        if (adminGroups == null %7C%7C adminGroups.length == 0) %7B%0A            return;%0A        %7D%0A%0A        String queryFilter = buildQueryFilter();%0A        Query query = new QueryBuilder()%0A                            .count(1)%0A                            .filter(queryFilter)%0A                         .build();%0A%0A        SCIMSearchResult%3CUser%3E result = connector.searchUsers(query, session.getAccesstoken());%0A%0A        if(result.getTotalResults() != 1) %7B%0A            throw new AccessDeniedException(%22The user not a member of an admin g
 roup
-s(
+.%22
 );%0A
+        %7D%0A    %7D%0A%0A    private String buildQueryFilter() %7B
 %0A   
@@ -2367,100 +2367,17 @@
 (%22%5C%22
-%22);%0A        if (adminGroups.length %3E 0) %7B%0A            queryString.append(%22
  AND 
+(
 %22);
-%0A        %7D
 %0A%0A  
@@ -2755,25 +2755,24 @@
       %7D%0A
-%0A
         
 SCIMSear
@@ -2767,273 +2767,72 @@
     
-SCIMSearchResult%3CUser%3E a = connector.searchUsers(new QueryBuilder().filter(queryString.toString()).build(), session.getAccesstoken());%0A%0A        if(a.getTotalResults() != 1) %7B%0A            throw new AccessDeniedException(%22No permissions to user admin gui%22);%0A        %7D
+queryString.append(%22)%22);%0A%0A        return queryString.toString();
 %0A   

refactor the code