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: 12:01:07
 * To change this template use File | Settings | File Templates.
 */
public class SingleEventTrigger implements Trigger
{
    private String event;
    private final List actions = new ArrayList();

    public WorkflowType getOwner()
    {
        return owner;
    }

    private WorkflowType owner = null;

    public int getId()
    {
        return id;
    }

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

    private int id;

    public SingleEventTrigger(String event, Action[] actions)
    {
        this.event = event;
        this.actions.addAll(Arrays.asList(actions));
        for (int i = 0; i < actions.length; i++)
        {
            Action action = actions[i];
            action.setTrigger(this);
        }
    }
    public SingleEventTrigger(String event, List actions)
    {
        this.event = event;
        this.actions.addAll(actions);
    }

    public SingleEventTrigger()
    {
        event = null;
    }

    public void clientDidOperation(Operation op, WorkflowClient client, User user)
    {
        if (op.getName().equals(event))
        {
            for (Iterator i = actions.iterator(); i.hasNext();)
            {
                Action a =  (Action) i.next();
                a.perform(client, user);
            }
        }
    }

    public List getActions()
    {
        return Collections.unmodifiableList(actions);
    }

    public String getFullDescription()
    {
        return "On the <b>" + owner.getOperationByName(event).getDescription() + "</b> step";
    }

    public boolean isConfigError()
    {
        return event == null || actions.size() == 0;
    }

    public void setOwner(WorkflowType owner)
    {
        this.owner = owner;
    }

    public void setEvent(String event)
    {
        this.event = event;
    }

    public String getEvent()
    {
        return event;
    }

    public void addAction(Action a)
    {
        a.setTrigger(this);
        actions.add(a);
    }

    public void deleteAction(int index)
    {
        actions.remove(index);
    }
}
