package DDrawing;


import java.util.Vector ;


public class DContainer extends DComponent implements DParent{
  Vector elements = new Vector();

// implementing DParent:
  public void repaint( DRectangle r ){
    DParent parent = getDParent();
    if( parent != null ) parent.repaint( r );
  }

  public void addDElement( DElement e ){
    if( elements.contains( e ) ) return;
    if( e instanceof DParent ){
      DParent he = (DParent)e, me = (DParent)this;
      if( he == me ) throw new
        IllegalArgumentException("Adding DParent to itself");
      me = getDParent();
      while( me != null ){
        if( he == me )throw new
          IllegalArgumentException("Adding DContainer's parent to itself");
        if( me instanceof DElement )
          me = ((DElement)me).getDParent();
        else me = null;
      }
    }
    elements.add( e );
    e.setDParent( this );
    DRectangle r = e.getRectangle();
    if( r != null ){
      adjustRect( r );
      if( e.isVisible() ) repaint( r );
    }
  }

  public boolean removeDElement( DElement e ){
    if( elements.removeElement( e ) ){
      repaint( e.getRectangle() );
      restore();
      return true;
    }
    return false;
  }

  public void removeAllDElements(){
    elements.removeAllElements();
    rectangle = null;
    repaint();
  }

// implementing DComponent:
  public void paint( DMeasures m ){
    DElement e;
    for( int i=0; i<elements.size(); i++ ){
      e = (DElement)elements.elementAt(i);
      if( e.isVisible() && m.getDRectangle().getIntersection( e.getRectangle() ) != null )
        e.paint( m );
    }
  }

  /**
   * this method adjusts max_rect if either a new elements has been added or
   * the area is restored
   *
   * @return a flag if max_rect has changed
   */
  private boolean adjustRect( DRectangle rect ){
    if( rectangle == null ){
      rectangle = (DRectangle)rect.clone();
      return !rect.isEmpty();
    }
    return rectangle.insert( rect );
  }

  /**
   * restores the container, that means that the rectangle is completely new calculated
   * this method is used after removing one of the elements
   */
  boolean restore(){
    DRectangle old;
    if( rectangle != null ) old = (DRectangle)rectangle.clone();
    else old = null;
    rectangle = null;
    for( int i=0; i<elements.size(); i++ )
      adjustRect( ( (DElement)elements.elementAt(i) ).getRectangle() );
    boolean changed = true;
    if( old != null ) changed = !old.equals( rectangle );
    return changed;
  }
}