package net.sf.jasperreports.engine.design;

import net.sf.jasperreports.engine.JRElementGroup;
import net.sf.jasperreports.engine.base.JRBaseElementGroup;
import net.sf.jasperreports.engine.design.events.JRChangeEventsSupport;
import net.sf.jasperreports.engine.design.events.JRPropertyChangeSupport;

public class JRDesignElementGroup extends JRBaseElementGroup implements JRChangeEventsSupport {
  private static final long serialVersionUID = 10200L;
  
  public static final String PROPERTY_ELEMENT_GROUP = "elementGroup";
  
  public static final String PROPERTY_CHILDREN = "children";
  
  private transient JRPropertyChangeSupport eventSupport;
  
  public void setElementGroup(JRElementGroup elementGroup) {
    Object old = this.elementGroup;
    this.elementGroup = elementGroup;
    getEventSupport().firePropertyChange("elementGroup", old, this.elementGroup);
  }
  
  public void addElement(JRDesignElement element) {
    element.setElementGroup((JRElementGroup)this);
    this.children.add(element);
    getEventSupport().fireCollectionElementAddedEvent("children", element, this.children.size() - 1);
  }
  
  public JRDesignElement removeElement(JRDesignElement element) {
    element.setElementGroup(null);
    int idx = this.children.indexOf(element);
    if (idx >= 0) {
      this.children.remove(idx);
      getEventSupport().fireCollectionElementRemovedEvent("children", element, idx);
    } 
    return element;
  }
  
  public void addElementGroup(JRDesignElementGroup elemGrp) {
    elemGrp.setElementGroup((JRElementGroup)this);
    this.children.add(elemGrp);
    getEventSupport().fireCollectionElementAddedEvent("children", elemGrp, this.children.size() - 1);
  }
  
  public JRDesignElementGroup removeElementGroup(JRDesignElementGroup elemGrp) {
    elemGrp.setElementGroup((JRElementGroup)null);
    int idx = this.children.indexOf(elemGrp);
    if (idx >= 0) {
      this.children.remove(idx);
      getEventSupport().fireCollectionElementRemovedEvent("children", elemGrp, idx);
    } 
    return elemGrp;
  }
  
  public JRPropertyChangeSupport getEventSupport() {
    synchronized (this) {
      if (this.eventSupport == null)
        this.eventSupport = new JRPropertyChangeSupport(this); 
    } 
    return this.eventSupport;
  }
}
