package fr.ensea.chart;

import java.util.Vector;

/**
 * Default implementation of the Curve2D interface. Offers synchronization capabilities for use by concurrent threads, as is
 * often the case in simulation code.
 */
public class DefaultCurve2D extends Vector implements Curve2D {

	private double minX, minY, maxX, maxY;
	private Point2D lastAdded;
	
	public DefaultCurve2D(){
		minX= minY= maxX= maxY=0; 
	}
	
	/**
	 * Adds the given (x,y) doublet to the curve, mainting x-axis ordering of points.
	 */
	public synchronized void addXY(double x, double y){
		Point2D pt = new Point2D(x,y);
		lastAdded = pt;
		if (size()==0){ // premier élément ajouté
			addElement(pt);
			minX = maxX = x;
			minY = maxY = y;
		}
		else { // preserve ordering along x-axis:
			if (x < minX) {
				minX = x;
				insertElementAt(pt,0);
			}
			else if (x > maxX) {
				maxX = x;
				addElement(pt);
			}
			else {
				for (int i=0; i<size(); i++){
					double x0 = getPoint(i).x;
					if (x0 == x) {
						//setElementAt(pt,i); // replace
						insertElementAt(pt,i);
						break;
					}
					else if (x0 > x) {
						insertElementAt(pt,i);
						break;
					}
				}
			}
			if (y < minY) minY = y;
			else if (y > maxY) maxY = y;
		}
		//System.out.println(this);
	}
	
	/**
	 * "Undo" the last "addXY" operation.
	 */
	public synchronized void undoAddXY(){
		if (lastAdded==null) return;
		removeElement(lastAdded);
		lastAdded=null;
	}

	/**
	 * returns the ith point
	 */
	public Point2D getPoint(int i){
		Point2D p = (Point2D)elementAt(i);
		if (p==null) p = new Point2D();
		return p;
	}
	
	/**
	 * Return the number of points
	 */
	public int getNbPoints(){
		return size();
	}
	
	/**
	 * Returns the minimum on the given axis
	 */
	public double getMin(int axis){
		switch (axis){
			case X_AXIS: return minX;
			case Y_AXIS: return minY;
			default: throw new IllegalArgumentException("Wrong axis index : "+axis);
		}
	}
	
	/**
	 * Returns the maximum on the given axis
	 */
	public double getMax(int axis){
		switch (axis){
			case X_AXIS: return maxX;
			case Y_AXIS: return maxY;
			default: throw new IllegalArgumentException("Wrong axis index : "+axis);
		}
	}
	
	/* // not supported by the jdk1.1.8 ! why ?
	public String toString(){
		String s = "Samples:\n";
		s += "* size:" + size() + "\n";
		s += "* x-axis: min="+minX+" max="+maxX+"\n";
		s += "* y-axis: min="+minY+" max="+maxY+"\n";
		for (int i=0; i<size(); i++) s+= getPoint(i)+" ";
		s += "\n";
		return s;
	}
	*/
	
	public static void main(String[] args){
		DefaultCurve2D c = new DefaultCurve2D();
		c.addXY(0,0);
		c.addXY(1,3);
		c.addXY(4,10);
		c.addXY(2,6);
	}
}
