package com.atlassian.confluence.extra.workflow;

import com.atlassian.user.User;

import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: Tomd
 * Date: 4/05/2005
 * Time: 11:49:07
 * To change this template use File | Settings | File Templates.
 */
public class DefaultOperation implements Operation
{

    private final String name;
    private final String description;
    private final List conditions;
    private int id;

    public DefaultOperation(Condition[] conditions, String name, String description)
    {
        this(Arrays.asList(conditions),name,description);
    }

    public DefaultOperation(List conditions, String name, String description)
    {
        this.conditions = conditions;
        this.name = name;
        this.description = description;
    }

    public String getName()
    {
        return name;
    }

    public int getId()
    {
        return id;  //To change body of implemented methods use File | Settings | File Templates.
    }

    public boolean isEditable()
    {
        return true;
    }

    public String getDescription()
    {
        return description;
    }

    public String getFullDescription()
    {
        return "<b>" + getDescription() + "</b>, available " + getConditionsDescription();
    }





    public boolean availableToUserAndClient(User user, WorkflowClient client)
    {
        if (user == null)
        {
            return false;
        }
        for (int i = 0; i < conditions.size(); i++)
        {
            Condition c =  (Condition) conditions.get(i);
            if (!c.allowed(user, client))
            {
                return false;
            }
        }
        return true;
    }

    public boolean isConfigError()
    {
        return false;
    }

    private String getConditionsDescription()
    {
        if (conditions.size() == 0)
        {
            return " always.";
        }
        StringBuffer sb = new StringBuffer();
        String sep = " when ";
        for (Iterator i = conditions.iterator(); i.hasNext();)
        {
            Condition c = (Condition) i.next();
            sb.append(sep);
            sb.append(c.getDescription());
            sep = " and ";
        }
        sb.append(".");
        return sb.toString();
    }

    public List getConditions()
    {
        return conditions;
    }

    public void deleteCondition(int index)
    {
        conditions.remove(index);
    }

    public void addCondition(Condition c)
    {
        conditions.add(c);
    }

    public void setId(int id)
    {
        this.id = id;
    }
}
