package testprocs;

import simulator.*;
import modules.color.*;
import modules.region.*;
import utils.*;
import java.awt.*;
import java.util.*;

// Persistent Node testing

public class RMTestProc implements ProcessorModule {
  public Symbol getName() { return Symbol.GetSymbol("RMTestProc"); }
  public void link(PortedProcessor p) {
    pp = p;
    pp.addClockListener(this);
    pp.openNetworkPort(this,uiPort);
    rm = (RegionManager)p.getModule("RegionManager");
    cm = (ColorModule)p.getModule("Color");
  }

  PortedProcessor pp; ColorModule cm; RegionManager rm;

  static final Symbol uiPort = Symbol.GetSymbol("UI");

  public void init() {
  }

  public static int count = 0;
  public static double probeID = Double.NaN;
  public static Object probeType = null;
  public boolean signalEvent(Symbol name,Object data) {
    boolean dirty = false;
    if(name==uiPort) {
      StringTokenizer tok = new StringTokenizer(data.toString());
      if(tok.hasMoreTokens()) { 
        String cmd=tok.nextToken();
        if(cmd.equals("region")) {
          Symbol s = Symbol.GetSymbol("default");
          if(tok.hasMoreTokens()) {
            s = Symbol.GetSymbol(tok.nextToken());
          } else {
          }
          if(s.equals("none")) {
            Iterator i = rm.getRegions().iterator();
            //while(i.hasNext()) { rm.deleteRegion(i.next()); count--; }
          } else {
            //if(!rm.inRegion(s)) { count++; rm.addRegion(s); }
          }
        } else if(cmd.equals("probe")) {
          if(tok.hasMoreTokens()) {
            Symbol s = Symbol.GetSymbol(tok.nextToken());
            if(s.equals("off")) probeID = Double.NaN;
            else { probeID = pp.getUID(); probeType=s; }
          } else {
            probeID = pp.getUID();
            if(probeType==null) probeType=Symbol.GetSymbol("default");
          }
        }
      }
    } else if(name==PortedProcessor.kClock) {
      int t = ((Integer)data).intValue();
      if(pp.getUID()==probeID) {
        //System.out.println("Region "+probeType+" Estimate: "
        //                   +rm.area(probeType)+" Actual: "+count);
      }

      // coloring: region hashID=color
      Set r = rm.getRegions();
      if(r.isEmpty()) cm.setColor(Color.blue);
      else {
        Object id = r.iterator().next();
        cm.setColor(cm.numberToColor(id.hashCode()%9)); // not-blue
        //if(rm.kludge_originate) cm.setColor(Color.white); // kludge connection
      }
    }
    return dirty;
  }

  public String toString() {
    return "RMTestProc";
  }
}


