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

package rec.house;

import java.awt.*;
import java.util.*;
import rec.core.*;
import rec.util.*;
import rec.sys.*;
import rec.geo.*;

public class WallMover extends Tracker implements Registerable
{
  public WallMover()
  {
  }
  
  public Iterator getInputTypes()
  {
    Vector v = new Vector();
    
    v.addElement( "rec.house.Region" );
    
    return v.iterator();
  }

  public Iterator getOutputTypes() 
  {
    return getInputTypes();
  }


  public void removed( Widget w )
  {
  }


  public void replaced( Widget ow, Collection nws )
  {
  }


  public void replaced( Widget ow, Widget nw )
  {
  }  



  /***
   * Called when w has been altered.
   *
   * @param w  The Widget after it has been altered.
   * @param t  The Transition that affected that Widget.
   */
  public void altered( Widget widget, Transition t )
  {
    Console.writeln( "WallMover sees " + widget + " being altered!" );
    Region r = (Region)widget;

    // we are only interested in move transitions.
    if ( ! (t instanceof MoveTransition ) )
      return;

    Console.writeln( "going to move all walls." );
    Iterator e = r.walls();
    while( e.hasNext() )
    {
      Wall w = (Wall)e.next();
      Console.writeln( "moving " + w );

      // first check to see if we need to split up (bordering
      // multiple regions)
      if ( w.full() )
	{
	  // we do.
	  Console.writeln( "full wall!" );
	  Wall nw = new Wall( surface,
			      w.getHead(),
			      w.getTail() );
	  
	  // clean up original wall
	  w.removeRegion( r );
	  r.removeWall( w );
	  
	  // fix up the new wall
	  nw.addRegion( r );
	  r.addWall( nw );
	  
	  nw.translate( ((MoveTransition)t).getChange() );
	  
	  // add--it will get recognized and the data structures will
	  // all get their shot.
	  surface.addWidget( nw, true);
	}
      else
	{
	  final GPoint del =  ((MoveTransition)t).getChange();
	  w.translate( del );
	  surface.alterWidget( w,
			       new FlipAlterTransition( surface, w ) {
	    public void doUndo()
	      {
		((Wall)getTargetWidget()).translate( new GPoint( del.x * -1,
					 del.y * -1 ) );
	      }
	    public void doDo()
	      {
		((Wall)getTargetWidget()).translate( del );
	      }
	    public String name()
	      {
		return "translate";
	      }
	  } );
	}
    }
  }
  
} // end WallMover
