import ddf.minim.*;
import ddf.minim.analysis.*;

class TravercingBall extends demoBase {
  Minim minim;
  AudioPlayer s;
  ddf.minim.analysis.FFT f;

  float specLow = 0.03;   // 3%
  float specMid = 0.125;  // 12.5%
  float specHi = 0.20;    // 20%

  
  int scoreLow = 0;
  int scoreMid = 0;
  int scoreHi = 0;

  ArrayList<Anomaly> a;
  Road road;

  boolean done;
  float startTime;
  float angle;
  
  public TravercingBall(AudioPlayer s, ddf.minim.analysis.FFT f) {
    this.s = s;
    this.f = f;
    startTime = - 1;
    
  
    road = new Road();
    a = new ArrayList<Anomaly>();
    a.add(new Anomaly((width / 2)));
  }
  
  
  void playDemo() {
    if (startTime == -1) {
      angle = 0;
      done = false;
      s.play(44 * 1000 + 500);
      startTime =  millis()/1000.0;
    }
    float t = millis()/1000.0 - startTime;
    if(t > 20) {
       if(angle < 90) {
         angle += 8;
       }
       else {
        s.pause();
        done = true;
       }
    }
    drawBackGround();
    calculateScores();
    doStuff();
    
  }
  
  void doStuff() {
    for (int i = a.size()-1; i >= 0; i--) {
    Anomaly h = a.get(i);
    if(scoreLow > 400){
      h.bounce();
    }
    
    h.draw(100+scoreLow, 100+scoreMid, 100+scoreHi, scoreLow / 4);
  } 

  road.update(100+scoreLow, 100+scoreMid, 100+scoreHi);
  }
  void calculateScores() {
    scoreLow = 0;
    scoreMid = 0;
    scoreHi = 0;
    f.forward(s.mix); // s = AudioPlayer
    for(int i = 0; i < f.specSize()*specLow; i++)
    {
      scoreLow += f.getBand(i);
    }
    
    for(int i = (int)(f.specSize()*specLow); i < f.specSize()*specMid; i++)
    {
      scoreMid += f.getBand(i);
    }
    
    for(int i = (int)(f.specSize()*specMid); i < f.specSize()*specHi; i++)
    {
      scoreHi += f.getBand(i);
    }
      
  }
  void drawBackGround() {
    rotateY(radians(angle));
    background( scoreLow / 100, scoreHi / 10, scoreMid / 10);
  }
  
  boolean isOver() {
    if(done) {
      s.close();
      startTime = -1;
    }
    return done;
  }
}