// (c) MIT 2003.  All rights reserved.

// $Id: RemoveTransition.java,v 1.3 2003/03/06 00:40:39 moltmans Exp $
// Time-stamp: <2000-03-11 18:59:36 moltmans>
package rec.sys;



import rec.util.*;
import java.util.*;

/**
 * Remove ONLY the widget in question (w).  Set the parent and child
 * links as if it was never there.
 */
public class RemoveTransition extends DoTransition
{
  protected Widget m_Widget;
  protected Collection m_ParentsOfWid;
  protected Collection m_ChildrenOfWid;
  private DoTransition m_ExpungeTransition;
  
  public RemoveTransition( Surface s, Widget w )
  {
    super( s );
    m_Widget = w;
    // just in case undo gets called before do
    m_ParentsOfWid = new HashSet();
    m_ChildrenOfWid = new HashSet();
  }


  /**
   * perform the transition 
   */
  public void doDo() 
  {
    // if it is not part of a litter, we can take it out of the tree,
    // otherwise it is too complicated.  This is only for efficiency, and
    // i am not sure it's even worhtwhile.  Once the widget is dead
    // and out of the widgetpool it won't be considered anymore, i don't
    // think, AS LONG AS ITS STRENGTH IS LOWER THAN THE SQUIGGLE
    if ( !m_Widget.inLitter() ) {
      m_ParentsOfWid = m_Widget.getParents();
      m_ChildrenOfWid = m_Widget.getChildren();
      
      Iterator it = m_ParentsOfWid.iterator();
      while ( it.hasNext() ) {
	Widget parent = (Widget)it.next();
	parent.removeChild( m_Widget );
	
	Iterator it2 = m_ChildrenOfWid.iterator();
	while ( it2.hasNext() ) {
	  FamilyMember child = (FamilyMember)it2.next();
	  child.removeParent( m_Widget );
	  child.addParent( parent );
	  parent.addChild( child );
	}
	
      }
    }

    // otherwise, just kill it
    m_Widget.die();
    m_ExpungeTransition = m_Surface.expunge();
    
  }

  /**
   * undoes the transition 
   */
  public void doUndo() 
  {
    m_ExpungeTransition.doUndo();
    m_Widget.revive();

    if ( !m_Widget.inLitter() ) {
      Iterator p_it = m_ParentsOfWid.iterator();
      Iterator c_it = m_ChildrenOfWid.iterator();
      
      while ( p_it.hasNext() ) {
	Widget parent = (Widget)p_it.next();
	parent.addChild( m_Widget );
	
	while ( c_it.hasNext() ) {
	  FamilyMember child = (FamilyMember)c_it.next();
	  child.removeParent( parent );
	  child.addParent( m_Widget );
	  parent.removeChild( child );
	}
      }
    }
  }

  /**
   * get the effects of the action without performing the do 
   */
  // for now this is just a string, soon it will be an action object
  // that can be more easily reasoned about.
  public String getAction()
  {
    return( "extract " + m_Widget + " but nothing else" );
  }

  ////////////////////////////////////////////////////////////////////////////

}

//////////////////////////////////////////////////////////////////////////////
