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

package rec.core.recognizers;

import edu.mit.sketch.geom.Point;
import edu.mit.sketch.geom.Polygon;
import java.util.Iterator;
import java.util.Vector;
import rec.core.widgets.WLine;
import rec.core.widgets.WPolyLine;
import rec.core.widgets.WPolygon;
import rec.geo.GPoint;
import rec.sys.Recognizer;
import rec.sys.Surface;
import rec.sys.Widget;


/**
 * 
 * <p>
 * Created:   Tue Mar 19 19:19:51 2002<br>
 * Copyright: Copyright (C) 2002 by MIT.  All rights reserved.<br>
 * 
 * @author <a href="mailto:moltmans@ai.mit.edu">Michael Oltmans</a>
 * @version $Id: ToolkitPolygonRecognizer.java,v 1.2 2003/03/06 00:40:47 moltmans Exp $
 **/

public class ToolkitPolygonRecognizer extends Recognizer {

  public boolean recognize( Surface s, Widget w )
  {
    ToolkitPolygonParser parser = new ToolkitPolygonParser( s, w );
    int tol = 20;

    if( ( w instanceof WPolyLine && parser.tryCombining( (WPolyLine)w, tol ) ) ||
	( w instanceof WLine && parser.tryCombining( (WLine)w, tol ) ) )
    {
      Polygon polygon = parser.getPolygon();

      GPoint[] points = new GPoint[ polygon.npoints - 1 ];
      
      // we don't include the last point because the first and the
      // last are the same for a closed polygon.
      for( int i = 0; i < polygon.npoints - 1; i++ ) {
	Point point = polygon.pointAt( i );
	points[i] = new GPoint( point.getX(), point.getY() );
      }


      WPolygon wpolygon = new WPolygon( points );
      s.replaceWidget( parser.getSubWidgets(), wpolygon, true );

      return true;
    }
    return false;
  }

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

    v.addElement( "rec.core.widgets.WPolyLine" );
    v.addElement( "rec.core.widgets.WLine" );

    return( v.iterator() );
  }

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

    v.addElement( "rec.core.widgets.WPolygon" );

    return( v.iterator() );
  }

}// ToolkitPolygonRecognizer
