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

// -*-Mode: Java-*- 
// $Id: AttachmentRule.java,v 1.6 2005/02/17 21:41:00 moltmans Exp $
// AttachmentRule.java -- 
// Author: Michael Oltmans <moltmans@ai.mit.edu> 
// Created: <Wed May 24 13:50:23 2000> 
// Time-stamp: <2005-02-16 14:03:43 moltmans> 
package rec.annotate.rules;

import rec.annotate.facts.*;
import java.util.*;
import rec.util.*;
import rec.tms.*;
import rec.sys.*;
import rec.simulate.widgets.*;

/**
 * Find attachments of bodies via constraints.
 **/
public class AttachmentRule extends AnnotateRule
{
  public LinkedList getTriggers() 
  {
    LinkedList triggers = new LinkedList();
    triggers.add( Type.PART_CONSTRAINT );
    triggers.add( Type.BODY );
    triggers.add( Type.BODY );
    return triggers;
  }

  public boolean match( LinkedList params ) 
  {
    PartConstraint part = (PartConstraint)params.get(0);
    if( part.getConstraint().numAttached() != 2 )
      return false;
    if( params.size() == 1 )
      return true;

    List bodies = part.getConstraint().getBodies();
    WSimBody b1 = (WSimBody)bodies.get(0);
    WSimBody b2 = (WSimBody)bodies.get(1);

    Body body1 = (Body)params.get(1);
    if( ! (body1.getBody().equals( b1 ) ||
	   body1.getBody().equals( b2 ) ) )
    {
      return false;
    }
    
    if( params.size() == 2 )
      return true;
    
    Body body2 = (Body)params.get(2);
    return ( !body2.equals( body1 ) &&
	     ( body2.getBody().equals( b1 ) ||
	       body2.getBody().equals( b2 ) ) );
  }

  public void run( Surface s, Notebook book, LinkedList params )
  {
    PartConstraint part = (PartConstraint)params.get(0);
    Body body1 = (Body)params.get(1);
    Body body2 = (Body)params.get(2);

    Attachment attach = new Attachment( part, body1, body2 );

//      DebugWindow.addLine( "Attach", "Attach: " + attach + " " +
//  			 params );
    book.myassert( attach, "AttachmentRule", params );
  }
}

