package com.atlassian.confluence.extra.workflow;

import com.atlassian.user.User;
import com.atlassian.user.User;
import com.atlassian.user.GroupManager;
import com.atlassian.user.Group;
import com.atlassian.user.search.page.PagerUtils;
import com.atlassian.user.search.page.Pager;

import java.util.HashSet;
import java.util.Arrays;
import java.util.Set;
import java.util.Iterator;

import bucket.user.UserAccessor;
import bucket.container.ContainerManager;

/**
 * Created by IntelliJ IDEA.
 * User: Tomd
 * Date: 23/05/2005
 * Time: 11:54:28
 * To change this template use File | Settings | File Templates.
 */
public class GroupSetCondition implements Condition
{
    private UserAccessor userAccessor;

    public Set getAllowedGroups()
    {
        return allowedGroups;
    }

    private Set allowedGroups;

    public GroupSetCondition(String[] groups)
    {
        allowedGroups = new HashSet(Arrays.asList(groups));
    }
    public boolean allowed(User user, WorkflowClient client)
    {
        Pager pager = getUserAccessor().getGroups(user);

        while (pager.iterator().hasNext())
        {
            Group group = (Group) pager.iterator().next();
            if (allowedGroups.contains(group))
                return true;
        }
        return false;
    }

    private UserAccessor getUserAccessor()
    {
        if (userAccessor == null)
            userAccessor = (UserAccessor) ContainerManager.getComponent("userAccessor");

        return userAccessor;
    }

    public String getDescription()
    {
        return " user is in " + getGroupsList();
    }

    private String getGroupsList()
    {
        StringBuffer sb = new StringBuffer();
        if (allowedGroups.size() == 0)
        {
            return "no groups";
        }
        else if (allowedGroups.size() == 1)
        {
            sb.append("group ");
        }
        else
        {
            sb.append("groups ");
        }
        String sep = "";
        for (Iterator i = allowedGroups.iterator(); i.hasNext();)
        {
            sb.append(sep);
            sb.append("<b>" + i.next() + "</b>");
            sep = ", ";
        }
        return sb.toString();
    }
}
