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

package rec.core.recognizers;

import edu.mit.sketch.geom.Approximation;
import edu.mit.sketch.geom.Point;
import edu.mit.sketch.geom.Polygon;
import edu.mit.sketch.toolkit.SimpleClassifier;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Vector;
import rec.core.widgets.WLine;
import rec.geo.GPoint;
import rec.sys.Recognizer;
import rec.sys.Squiggle;
import rec.sys.Surface;
import rec.sys.Widget;


/**
 * 
 * <p>
 * Created:   Mon Mar 18 15:45:38 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: ToolkitFacitedLineBreakerRecognizer.java,v 1.2 2003/03/06 00:40:47 moltmans Exp $
 **/

public class ToolkitFacitedLineBreakerRecognizer extends Recognizer
{
  
  public ToolkitFacitedLineBreakerRecognizer()
  {
  }

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

    //    Console.writeln( "line recognizer activated" );

    SimpleClassifier c = squiggle.getClassifier();

    // the classifier may be null if there was not enough data for it to operate
    // also check that this is either a polygon or close to one
    if( c == null ||
	c.getPolygonError() > c.getEllipseError() ||
	c.getPolygonError() > c.getLineError() )
    {
      return false;
    }

    HashSet lines = new HashSet();
    Polygon polygon = c.getPolygonApproximation();

    Point pPoint1 = polygon.pointAt( 0 );
    GPoint gPoint1 = new GPoint( pPoint1.getX(), pPoint1.getY() );

    Point pPoint2 = null;
    GPoint gPoint2 = null;

    for( int i=1; i < polygon.npoints; i++ ) {
      pPoint2 = polygon.pointAt( i );
      gPoint2 = new GPoint( pPoint2.getX(), pPoint2.getY() );

      WLine l = new WLine( gPoint1, gPoint2 );
      lines.add( l );
      gPoint1 = gPoint2;
    }

    s.replaceWidget( squiggle, lines, true );

    return true;
  }

  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.core.widgets.WLine" );

    return( v.iterator() );
  }
  
}// ToolkitFacitedLineBreakerRecognizer

