import processing.sound.*;
import ddf.minim.*;

class spinnerDemo extends demoBase {
  
  processing.sound.SoundFile sample;
  processing.sound.Amplitude rms;
  
  // Declare a scaling factor
  float scale=5;
  
  // Declare a smooth factor
  float smooth_factor=0.25;
  
  // Used for smoothing
  float sum;
  
  PShape spinner;
  
  float startTime = 30;
  
  float demoStartTime = -1;
  float spinSpeed = 2.66*PI;
  PImage img;

  
  boolean done;
  
  public spinnerDemo(SoundFile sample, Amplitude rms, PImage img, PShape spinner) {    
    this.sample = sample;
    this.rms = rms;
    this.img = img;
    this.spinner = spinner;
  }
  
  void playDemo() {
    
  if(demoStartTime == -1){
    demoStartTime = (millis()/1000.0);   
    sample.loop();
    sample.jump(startTime);
    // Create and patch the rms tracker
    rms.input(sample);
  }
  float t = (millis()/1000.0) - demoStartTime + startTime;
  //println(t);
  background(0);
  lights();  
  
  translate(width/2, height/2, 0);
  stroke(255);
  
  // smooth the rms data by smoothing factor
  sum += (rms.analyze() - sum) * smooth_factor;
  
    float stage1 = 40;
    float stage2 = 48;
    float stage3 = 50;
    float stage4 = 65;
    
    if(t<stage1){
      rotateX(-PI/6);
      rotateY(spinSpeed*t);
      scale(sum*5);
      drawSpinner();
      //drawTriangle();
    }else if(t<stage2){
      rotateX(-PI/6);
      rotateY(spinSpeed*t);
      scale(sum*5);
      pushMatrix();
      float disp = (t-stage1)*100;
      translate(disp, 0, 0);
      drawSpinner();
      popMatrix();
      pushMatrix();
      translate(-disp, 0, 0);
      drawSpinner();
      popMatrix();
    }else if(t<stage3){
      rotateX(PI/2);
      rotateY(spinSpeed*t);
      scale(0.25);
      drawSpinner();
    }else if(t<stage4){
      rotateX(PI/2);
      rotateY(spinSpeed*t);
      scale(0.25);
      float disp = (t-stage3)*100;
      int counter = 0;
      for(float i = 0; i < 2*PI; i+=(PI/3)){
        pushMatrix();
        translate(disp*sin(i),0,disp*cos(i));
        if(counter%2 == 0) rotateY(spinSpeed*t);
        drawSpinner();
        popMatrix();
        counter++;
      }
    }else{
      done = true;
      textSize(32);
      fill(0, 102, 153);
      float t_diff = (t-stage4);
      text("Speed: " + (spinSpeed+t_diff) , -width*0.5+50, -height*0.5+50);
      rotateX(PI/2);
      rotateY((spinSpeed+t_diff)*t);
      scale(10);
      scale(sum);
      drawSpinner();
    }
  }
  
  
  boolean isOver() {
    if(done){
      sample.stop();
    }
    return done;
  }
  
  void drawSpinner(){
    pushMatrix();
    scale(100);
    shape(spinner, 0, 0);
    popMatrix();
  }
  
}