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

package rec.simulate.widgets;
// -*-Mode: Java-*- 
// WSimAnchor.java -- 
// Author: Christine Alvarado <calvarad@ai.mit.edu> 
// Maintainer: Christine Alvarado <calvarad@ai.mit.edu> 
// Version: 
// Created: <Wed May 26 14:08:41 1999> 
// Time-stamp: <2001-09-10 18:29:08 moltmans> 
// Keywords: 

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

public abstract class WSimAnchor extends WSimConstraint
{

  public WSimAnchor( GPoint center, double size )
  {
    setDefaultColor( "anchor", "sim_constraint" );
    m_body1 = null;
    setEnglishName( "Anchor" );

    // fill up the components
    m_Components = new GShape[2];
    double corner = size / Math.sqrt(8);
    m_Components[0] = new GSegment( new GPoint( -1 * corner, corner ),
				    new GPoint( corner, -1 * corner ) );
    m_Components[1] = new GSegment( new GPoint( corner, corner ),
				    new GPoint( -1 * corner, -1 * corner ) );

    m_Size = size;
    //m_Center = getLocation().getCenter();

    move( center );
    
    m_Name = "Anchor" + getId();

  }

  // the anchor must be attached to one body
  public boolean attach( WSimBody b )
  {
    if( m_body1 != null ) { 
      Console.writeln( "Anchor already attached to a body.  Cannot attach to body " 
		       + b.getName() );
      return false;
    } 
  // check to see if anchor is inside the body in question
    if ( b.contains( getLocation().getCenter(), 0 ) ) {
      m_body1 = b;
      return true;
    }
    return false;
    
  }

  public void detach() 
  {
    m_body1 = null;
  }

  public int numAttached()
  {
    if ( m_body1 == null ) {
      return 0;
    }
    else {
      return 1;
    }
  }

  public List getBodies() 
  {
    List list = new ArrayList( numAttached() );
    if( m_body1 != null )
      list.add( m_body1 );
    return list;
  }

  public GPoint getAttachmentPoint( WSimBody body ) 
  {
    if( body.equals( m_body1 ) )
      return getLocation().getCenter();
    else
      return null;
  }
  
  protected WSimBody m_body1;  

} 
