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

// $Id: TemporalReasoner.java,v 1.5 2003/05/09 21:22:32 moltmans Exp $
// Time-stamp: <2003-05-09 16:43:04 moltmans>
package rec.core.reasoners;



import java.io.*;
import java.util.*;
import rec.util.*;
import rec.sys.*;
import rec.core.widgets.*;
import rec.simulate.widgets.*;

public class TemporalReasoner extends Reasoner 
{
  public TemporalReasoner()
  {
    super();
  }

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

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

    return v.iterator();
  }

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

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

    return v.iterator();
  }

  // match if the weaker type has multiple parts which are not from
  // the same time period, while the strong type has all parts from
  // similar time period.
  public boolean match( Surface s, Widget stronger, Widget weaker )
  {
    boolean str_gap = false;
    boolean wea_gap = false;
//      // i.e. you can have n intervening widgets
//      int gap_tolerance = 3;
    
//      int str_gap = 0;
//      int wea_gap = 0;
    
    // get the base squiggles of each widget
    Object[] str_temp = stronger.getRootAncestors().toArray();
    Object[] wea_temp = weaker.getRootAncestors().toArray();

    java.util.Comparator comp = new WidgetTimeComparator();
    Arrays.sort( str_temp, comp );
    Arrays.sort( wea_temp, comp );

    List str_roots = Arrays.asList( str_temp );
    List wea_roots = Arrays.asList( wea_temp );
    
    Vector all_wids = new Vector ( s.getAllWidgets() );

    Widget first = (Widget)str_roots.get( 0 );
    Widget last = (Widget)str_roots.get( str_roots.size() - 1 );

    int start = all_wids.indexOf( first ) + 1;
    int finish = all_wids.indexOf( last );

    while ( start <= finish ) {
      Widget w = (Widget)all_wids.get( start );
      if ( w instanceof WUtterance ) {
	continue;
      }
      else {
	if ( !w.relatedToOneOf( str_roots ) ) {
	  str_gap = true;
	  break;
//  	  str_gap++;
	}
      }
      start++;
    }

    if ( str_gap == true ) {
//      if ( str_gap > gap_tolerance ) {
      return false;
    }

    // repeat for weak side
    first = (Widget)wea_roots.get( 0 );
    last = (Widget)wea_roots.get( wea_roots.size() - 1 );

    start = all_wids.indexOf( first ) + 1;
    finish = all_wids.indexOf( last );
    while ( start <= finish ) {
      Widget w = (Widget)all_wids.get( start );
      if ( w instanceof WUtterance ) {
	continue;
      }
      else {
	if ( !w.relatedToOneOf( wea_roots ) ) {
//  	  wea_gap++;
	  wea_gap = true;
	  break;	}
      }
      start++;
    }

    if ( wea_gap == false ) {
//      if ( wea_gap > gap_tolerance ) {
      return false;
    }
    else {
      return true;
    }
  }
}
