/**
 *
 *created by Przemek
 *
 */

package JSciDraw.physics.forces;

import JSciDraw.physics.*;
import JSciDraw.interfaces.*;
import JSci.maths.*;
import JSci.physics.*;
import java.awt.*;
import java.awt.geom.*;
import java.util.*;

public class FreeSpring implements Drawable2D, Moveable2D{
    private final double coefficient;
    private final ClassicalParticleV2D part1;
    private final ClassicalParticleV2D part2;
    private final double bL;
    protected Color color=Color.green;
    
    public FreeSpring(ClassicalParticleV2D p1, ClassicalParticleV2D p2, double coeff, double bL) {
                coefficient = coeff;
                part1=p1; part2=p2;
                this.bL=bL;
                part1.addExtForce(createForce(part1));
                part2.addExtForce(createForce(part2));
        }
    
    private class Force extends JSci.physics.Force {
       private final ClassicalParticleV2D p1;
       private final ClassicalParticleV2D p2;
       private int which=0; //1 - p1, 2 - p2
       public Force(ClassicalParticleV2D p) {
            this.p1 = part1;
            this.p2 = part2;
            if (p==p1) which=1;
            if (p==p2) which=2;
       }
       public AbstractDoubleVector getVector(double t) 
       {
          AbstractDoubleVector wodz;
          if (which==1){
            wodz =((p2.getPosition()).subtract(p1.getPosition()));
          }  else if (which==2){
              wodz =((p1.getPosition()).subtract(p2.getPosition()));
            }  else{ 
                return new Double2Vector(0,0);
               }
          double wart=wodz.norm();
          wodz.normalize();
          return wodz.scalarMultiply(coefficient*(wart-bL));
      }
    }
   
    public double energy() {
       AbstractDoubleVector wodz =((part2.getPosition()).subtract(part1.getPosition()));
       double dX=wodz.norm()-bL;
       return dX*dX*coefficient/2.;
    }
   
    public Force createForce(ClassicalParticleV2D p) 
    {
        return new Force(p);
    }
      
    public void draw2D(Graphics2D g2D){
        g2D.setColor(color);
        g2D.drawLine((int)part1.getPosition().getComponent(0),(int)part1.getPosition().getComponent(1),
        (int)part2.getPosition().getComponent(0),(int)part2.getPosition().getComponent(1));
    }
    public void erase2D(Graphics2D g2D){
        g2D.setColor(Color.white);
        g2D.drawLine((int)part1.xOl,(int)part1.yOl,
        (int)part2.xOl,(int)part2.yOl);
    }
    
    public void move2D(double dt) {}
    public Color getColor() { return color; }
    public void setColor(Color c) { color = c; }
    public void calculateForces(double dt) {}
    public void addExtForce(JSci.physics.Force f) {}
    
}


