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

// $Id: SelectPolyRecognizer.java,v 1.7 2003/03/06 00:40:47 moltmans Exp $
// Time-stamp: <2001-04-03 19:27:18 moltmans>
package rec.core.recognizers;



////////////////////////////////////////////////////////////////////////////
//
// FILE:	SelectPolyRecognizer.java
//
// AUTHOR:	Manoj D. Muzumdar
//		archon@ai.mit.edu
//
// DATE:	June, 1998
//
// COPYRIGHT:	Massachusetts Institute of Technology
//		All rights reserved.
//
// PURPOSE:	Drawing recognition
//
// HISTORY:     September, 1998
//              MDM
//              modified to fit with new recognition model
//
/////////////////////////////////////////////////////////////////////////////


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

public class SelectPolyRecognizer extends SelectionRecognizer
{
  public SelectPolyRecognizer()
  {
  }

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

  /**
   * This recognizes polygons when selected by clicking in the interior.
   */
  public boolean recognize( Surface s, Widget w )
  {
    WClick c = (WClick)w;

    //    s.removeWidget( c );
    GPoint pf = c.getLocation().getCenter();
    
    VisibleWidget vw = (VisibleWidget)selectPoly( s, pf );

    if( vw == null )
      return( false );

    //Console.writeln( vw + " selected" );

    WGroup single = new WGroup();
    single.add( vw );
    WSelection sl = new WSelection( single, false );
    s.replaceWidget( w, sl );
    
    return( true );
  }

  public static VisibleWidget selectPoly( Surface s, GPoint pt )
  {
    final GPoint pf = pt;
    GeometryCalculator calc = new GeometryCalculator( s );

    VisibleWidget vw = calc.findWidget( new GeoFunction() {
	public boolean check( VisibleWidget w ) {
	  if ( w instanceof WPolygon )
	    return( ((WPolygon)w).contains( pf, 0.0 ) );
	  else
	    return false;
	}
    } );

    return vw;
  }


}

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