import javax.swing.Timer;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class Simulator implements ActionListener {
   protected BlockSpringConfiguration bsConfig;
   private float t;  // Simulation time time
   private Timer pase;
   private float delta_t;         // in seconds
   private float samplingPeriod;  // in seconds
   
   
   public Simulator (BlockSpringConfiguration bsc) {
      t=0;
      bsConfig = bsc;
      delta_t = 0.0001f;        // 1 [ms]
      samplingPeriod = 0.08f;  //   80 [ms]
   }
   
   public Simulator (BlockSpringConfiguration bsc, float RefreshTime, float DeltaTime) { //Se agreg� este constructor para pasar los par�metros por HTML.
      t=0;
      bsConfig = bsc;
      delta_t = DeltaTime;        
      samplingPeriod = RefreshTime;  
   }
   
   /**
    * Se setea la gravedad.
    * @param g Gravedad. En la tierra es 9,8[m/s*s] aproximadamente.
    */
   public void setGravity(float g) {
      bsConfig.gravity(g);
   }

   public void setDelta_t(float delta) {
      delta_t = delta;
   }
   public void setSamplingPeriod (float sp) {
      samplingPeriod = sp;
      if (pase!=null)
         if (pase.isRunning()){
            stop();
            start();
         }   
   }
   public void start() {
      if(pase==null || !pase.isRunning()){
      t=0;
      pase = new Timer((int)(samplingPeriod*1000), this);
      pase.start();
      }
   }
   public void stop(){
      if (pase!=null)
         pase.stop();
   }
   /**
    * Resetea la simulacion.
    */
   public void reset(){
      bsConfig.gravity(0);
      bsConfig.reset();
      if (pase!=null){  
         pase.restart();  
         pase.stop();

      }
   }
   /**
    * Elimina el ultimo elemento fisico ingresado siempre y cuando la simulacion
    * se encuentre detenida (STOP).
    */
   public void resetLast(){
      if(pase==null || !pase.isRunning()){
      bsConfig.resetLast();
      }
   }
   public void actionPerformed (ActionEvent e) {
      Vector2D pos;
	   float nextStop=t+samplingPeriod;
      for (; t<nextStop; t+=delta_t){
         bsConfig.computeNextState(delta_t);
         bsConfig.updateState();
         
      }
      bsConfig.time(samplingPeriod);
   }
}
