import processing.core.PApplet;
import processing.core.PVector;

// Particles + Forces
// Daniel Shiffman <http://www.shiffman.net>

// A very basic Repeller class
class Repeller {
  PApplet parent;
  
  // Gravitational Constant
  float G = 100;

  // Location
  PVector loc;

  float r = 15;

  // For mouse interaction
  boolean dragging = false; // Is the object being dragged?
  boolean rollover = false; // Is the mouse over the ellipse?
  PVector drag;  // holds the offset for when object is clicked on

  Repeller(PApplet _p, float x, float y)  {
	  parent = _p;
	  loc = new PVector(x,y);
	  drag = new PVector(0,0);
  }

  public void display() {
    parent.noStroke();
    if (dragging) parent.fill (0,255,255);
    else if (rollover) parent.fill(150);
    else parent.fill(0,150,0);
    parent.ellipse(loc.x,loc.y,r*2,r*2);
  }

  // Calculate a force to push particle away from repeller
  PVector pushParticle(Particle p) {
    PVector dir = PVector.sub(loc,p.loc);      // Calculate direction of force
    float d = dir.mag();                       // Distance between objects
    dir.normalize();                           // Normalize vector (distance doesn't matter here, we just want this vector for direction)
    d = PApplet.constrain(d,5,100);                     // Keep distance within a reasonable range
    float force = -1 * G / (d * d);            // Repelling force is inversely proportional to distance
    dir.mult(force);                           // Get force vector --> magnitude * direction
    return dir;
  }  

  
  public void setLoc(PVector _l){
    this.loc.set(_l);
  }
  
  public PVector getLoc(){
    return loc;
  }
  
  public PVector addLoc(PVector _l){
    loc.add(_l);
    return this.getLoc();
  }
  
  // The methods below are for mouse interaction
  void clicked(int mx, int my) {
    float d = PApplet.dist(mx,my,loc.x,loc.y);
    if (d < r) {
      dragging = true;
      drag.x = loc.x-mx;
      drag.y = loc.y-my;
    }
  }

  void rollover(int mx, int my) {
    float d = PApplet.dist(mx,my,loc.x,loc.y);
    if (d < r) {
      rollover = true;
    } 
    else {
      rollover = false;
    }
  }

  void stopDragging() {
    dragging = false;
  }

  void drag() {
    if (dragging) {
      loc.x = parent.mouseX + drag.x;
      loc.y = parent.mouseY + drag.y;
    }
  }


}


