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

////////////////////////////////////////////////////////////////////////////////
//
// FILE:	SpringRecognizer.java
//
// AUTHOR:	Manoj D. Muzumdar
//		archon@ai.mit.edu
//
// DATE:	Mar 99
//
// COPYRIGHT:	Massachusetts Institute of Technology
//		All rights reserved.
//
// PURPOSE:	Mechanical engineering drawing recognition
//
// HISTORY:     Mar 99  archon  created
//
////////////////////////////////////////////////////////////////////////////////

package rec.meche;

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

public class SpringRecognizer extends Recognizer
{
  public static WMSpring isSpring( Squiggle s )
  {
    int num = s.getNumberOfPoints();

    // Make sure there are at least two points in the squiggle.

    if( num < 2 )
      return( null );

    // this watches out for the fact that a line segment cannot start
    // and end at the same place.
    if ( s.getFirstPoint().equals( s.getLastPoint() ) ) {
      return null;
    }
    
    GSegment line = new GSegment( s.getFirstPoint(), s.getLastPoint() );

    if( s.getLength() < 2.0 * line.getLength() )
      return( null );

    for( int i = 0; i < num; ++i ) {

      GPoint p = s.getPointAt( i );
      GPoint perp = line.perpendicular( p );

      if( Geometry.distance( p, perp ) >= line.getLength() / 3.0 )
        return( null );
    }

    return( new WMSpring( s.getLocation().getCenter(),
			  Geometry.angle( s.getFirstPoint(),
					  s.getLastPoint() ),
			  line.size(),
			  null ) );
  }

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

  public SpringRecognizer()
  {
  }

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

  public boolean recognize( Surface s, Widget w )
  {
    Squiggle sq = (Squiggle)w;

    WMSpring part = isSpring( sq );

    if( part != null ) {

      s.removeWidget( sq );
      s.addWidget( part );

      return( true );
    }

    return( false );
  }

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

  public Iterator getInputTypes()
  {
    Vector v = new Vector();

    v.addElement( "rec.sys.Squiggle" );

    return( v.iterator() );
  }

  public Iterator getOutputTypes()
  {
    Vector v = new Vector();

    v.addElement( "rec.meche.WMSpring" );

    return( v.iterator() );
  }
}

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