package modules.color;

import utils.*;
import simulator.*;
import java.util.*;
import java.awt.*;

// will only color itself once per tick
public class ColorModule implements ProcessorModule {
  PortedProcessor pp;

  public Symbol getName() { return Symbol.GetSymbol("Color"); }
  public void link(PortedProcessor p) { 
    pp = p; 
    pp.addClockListener(this);
  }
  public void init() {} // nothing needs to happen

  boolean flashing = false;
  boolean flashable = true;
  public boolean signalEvent(Symbol name,Object data) {
    boolean changed = false;
    if(name==PortedProcessor.kClock) {
      if(!flashing) {
        changed = color.equals(pp.getColor());
        pp.colorme(color);
      }
    } else if(name==Simulator.kDelay) { // ending a flash
      if(flashing) {
        flashing = false;
        pp.colorme(color);
        pp.timer(this,kFlashTime,null);
        changed = true;
      } else {
        flashable = true;
        changed = true;
      }
    }
    return changed;
  }

  Color color = Color.blue;
  public void setColor(Color c) { color = c; }
  // flashes can have no more than 50% duty cycle
  static final double kFlashTime = 0.05;
  public void flash() { flash(Color.white); }
  public void flash(Color c) {
    if(color.equals(c)) {
      pp.colorme(Color.black);
    } else {
      pp.colorme(c);
    }
    flashable = false;
    flashing = true;
    pp.timer(this,kFlashTime,null);
  }
  public Color randomColor() {
    return numberToColor((int)Math.floor(Math.random()*10));
  }
  public Color numberToColor(int n) {
    if(n<0) { n=(n%10)+10; }
    switch(n%10) {
    case 0: { return Color.cyan; }
    case 1: { return Color.pink; }
    case 2: { return Color.green; }
    case 3: { return Color.white; }
    case 4: { return Color.orange; }
    case 5: { return Color.lightGray; }
    case 6: { return Color.magenta; }
    case 7: { return Color.red; }
    case 8: { return Color.yellow; }
    case 9: { return Color.blue; }
    }
    System.out.println("Number To Color failure! Shouldn't ever happen!");
    return null;
  }
  public String toString() { return "Color: "+color.toString(); }
}

