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

package rec.fun;

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

public class ScratchOutRecognizer extends Recognizer
{

  public ScratchOutRecognizer()
  {
  }


  /**
   * If the squiggle is a squiggly mess (i.e. much longer than
   * the bounding box would suggest) then it is a scratchout.
   */
  public static boolean isScratchOut( Surface sur, Squiggle sq )
  {
    HitGrid g = new HitGrid( sur, 3, sq );
    sur.unregister( g, sq );

    //    sur.addWidget( g );    
    
    if ( ! ( sq.getSpeed() < 2 * sur.getAverageStrokeSpeed() ) )
      {
	Console.writeln( "not fast enough for scribble." );
	return false;
      }

    double dens = g.double_density();
    Console.writeln( "Grid density = " + dens + ", need 0.65" );


    if (! g.hitAt( 2, 2 ) )
      {
	Console.writeln( "Not hit in middle." );
	return false;
      }

    if ( dens > 0.65 )
      return true;
    
    return false;

    /*double ln = sq.getLength();

    Rectangle rec = sq.getBounds();

    double perim = 2 * rec.width + 2 * rec.height;

    if ( ln > 1.5 * perim )
      return true;

    return false;*/
  }

  public boolean recognize( Surface s, Widget w )
  {
    if ( isScratchOut( s, (Squiggle)w ) )
      {

	Console.writeln( "found a scratch out." );
	GeometryCalculator calc = new GeometryCalculator( s );
	
	boolean hit_one = false;

	Location lc = ((Squiggle)w).getLocation();
	double rad = 0.75 * lc.getRadius();
	VisibleWidget vw = null;


	boolean done = false;

	while( !done
	       && ( vw = calc.findClosestWithCheck( lc.getCenter(),
						 new NotMeFilter( w ) ) )
	       != null )
	  {
	    if ( Geometry.distance( vw.getLocation().getCenter(),
				    lc.getCenter() )
		 < rad )
	      {
		Console.writeln( vw + " scratched out... deleting..." );

		hit_one = true;
		
		s.removeWidget( vw );
	      }
	    else
	      done = true;
	  }
	
	if ( hit_one )
	  {
	    s.removeWidget( w );
	    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();

    return( v.iterator() );
  }
}


