package graphicsDomain;

import java.awt.*;
import java.awt.geom.*;

public class DrawCrossHair
{
    private GraphicsFacade graphFacade; //Needed to notify listeners

    public DrawCrossHair(GraphicsFacade graph)
    {
	graphFacade = graph;
    }

    public void draw(GraphMetrics metrics, Graphics2D g2)
    {
	int currX = metrics.getCurrX();
        Point[] points = metrics.getPixelArray(metrics.getGraphData().getX(),
                                               metrics.getGraphData().getY());
	int xSize = metrics.getXSize();
	int ySize = metrics.getYSize();
	int borderSize = metrics.getBorderSize();

	/* Draw cursor */
	// First find index of closest x data point
	if ((currX > borderSize) && (currX < xSize-borderSize))
	{
	    // find closest data value from xScaled
            int minIdx = 0;
            double minDist = Math.abs(currX - points[0].x);
            double currDist=minDist;
            for (int i = 1; i < points.length; i++)
            {
               currDist = Math.abs(currX - points[i].x);
               if(currDist < minDist)
               {
                   minDist = currDist;
                   minIdx = i;
               }
            }
            // set xData to xVals at minimum distance
	    double xdata = metrics.getXValue(points[minIdx].x);
	    double ydata = metrics.getYValue(points[minIdx].y);
	    graphFacade.graphPointUpdated(xdata,ydata,true);

	    // draw large cursor marker on graph
	    Line2D xLine = new Line2D.Float (borderSize, points[minIdx].y,
					     xSize-borderSize,points[minIdx].y);
	    Line2D yLine = new Line2D.Float (points[minIdx].x, ySize-borderSize,
					     points[minIdx].x,borderSize);
            g2.draw(xLine);
            g2.draw(yLine);
        }
	else
	{
	    graphFacade.graphPointUpdated(0,0,false);

	}
    }
}
