// JDraw - Line class
// Written by Jim Calciano, Melanie Lear, and PJ Waskiewicz
// November 18, 1998
// Class which creates a Line object from the abstract class DrawObject

import java.awt.*;

public class Line extends DrawObject{
  private int x1, y1, x2, y2;
  private Color color;
  // Method to return a string of all attributes of the line to be written
  // to a file
  public String returnString(){
    return (new String("line" + " " + x1 + " " + y1 + " " + 
                   x2 + " " + y2 + " " + color.getRed() + "," +
                       color.getGreen() + "," + color.getBlue()));
  }
  // Constructor for when the line is drawn and opened from a file
  public Line(int x1, int y1, int x2, int y2, Color color){
    this.x1 = x1;
    this.x2 = x2;
    this.y1 = y1;
    this.y2 = y2;
    this.color = color;
  }
  public void paint(Graphics g){
    g.setColor(color);
    g.drawLine(x1, y1, x2, y2);
  }
  public Point firstSelPoint(){
    return(new Point(x1,y1));
  }
  public Point secondSelPoint(){
    return(new Point(x2,y2));
  }
  public Color selColor(){
    return color;
  }
  public void setSelColor(Color c){}
  public boolean areYouSelected(){
    return false;
  }
  public void youAreSelected(boolean b){
  }
  public boolean getIfObjectClicked(){
    return false;
  }
  public boolean getIfHandleClicked(){
    return false;
  }
  public boolean intersects(int x, int y){
    // Using the point-on-a-line formula to determine whether a point
    // intersects our line, we must account for lines of undefined
    // slope, i.e. vertical lines.  We also allow some "slack," which is
    // defined as 4 pixels in this case.  So a user does not have to be
    // exact when clicking the line to select it.
    int bigy;
    int smally;
    int bigx;
    int smallx;
    double m;
    if(y1<y2){
      smally=y1;
      bigy=y2;
    }
    else{
      smally=y2;
      bigy=y1;
    }
    if(x1<x2){
      smallx=x1;
      bigx=x2;
    }
    else{
      smallx=x2;
      bigx=x1;
    }
    // This is the case when the line is vertical.  Note this does not
    // need to use the point on a line function, just a range check
    if((x2-x1>=-10)&&(x2-x1<=10)){
      return ((smally-4 <= y) && (bigy+4 >= y) && ((x2+4 >= x)&&(x2-4 <= x)));
    }
    // This is when the line is horizontal
    else if(y2-y1==0)
      return ((smallx-4 <= x) && (bigx+4 >= x) && ((y2+4 >= y)&&(y2-4 <= y)));
    // And this is when it is just something else 
    // (stuck in the middle with you...)
    else{
      m = ((double)(y2 - y1)/(double)(x2-x1));
      // Using a modification of the point-slope formula, 
      //check multiple lines for the
      // point clicked being on one of the lines, so then 
      //being in a "slack" range
      for(int i=(x1-6);i<=(x1+6);i++){
        for(int j=(y-4);j<=(y+4);j++){
          if(j==(int)(m*(x-i)+y1)&&((smallx<=x)&&(bigx>=x)))
            return true;
        }
      }
      return false;
    }
  }
}