package DDrawing;

import java.awt.*;


/**
 * @author  mkron
 */
public class DPointSet extends DComponent{
	private double[] x;
	private double[] y;
	private boolean connected = false;
	private int size = 0;

	public DPointSet( int initial_capacity ){
		if( initial_capacity < 1 ) initial_capacity = 1;
		x = new double[ initial_capacity ];
		y = new double[ initial_capacity ];
	}

	public void paint( DMeasures m ){
		Graphics g = m.getGraphics();
		Color old_color = g.getColor();
		if( color != null ) g.setColor( color );
		else g.setColor( DEFAULT_COLOR );
		if( connected && size > 1 ){
			Point p1, p2;
			p1 = m.getPoint( x[0], y[0] );
			for( int i=1; i<size; i++ ){
				p2 = m.getPoint( x[i], y[i] );
				g.drawLine( p1.x, p1.y, p2.x, p2.y );
				p1 = p2;
			}
		}
		else{
			Point p;
			for( int i=0; i<size; i++ ){
				p = m.getPoint( x[i], y[i] );
				g.drawLine(p.x - 1, p.y - 1, p.x + 1, p.y + 1);
				g.drawLine(p.x + 1, p.y - 1, p.x - 1, p.y + 1);
			}
		}
		g.setColor( old_color );
	}

	public void addDPoint( DPoint p ){
		addDPoint( p.x, p.y );
	}

	public void addDPoint( double x, double y ){
		if(y>10000.) {
			System.err.println("refusing y="+y);
			return;
		}
		if( ++size > this.x.length ){
			int oldL = this.x.length;
			double[] newV = new double[ oldL * 2 ];
			System.arraycopy( this.x, 0, newV, 0, oldL );
			this.x = newV;
			newV = new double[ oldL * 2 ];
			System.arraycopy( this.y, 0, newV, 0, oldL );
			this.y = newV;
		}
		this.x[ size - 1 ] = x;
		this.y[ size - 1 ] = y;

		if( size == 1 ) rectangle = new DRectangle( x, y, 0, 0 );
		else rectangle.insert( new DPoint( x, y ) );

		repaint();
	}

	public void setConnected( boolean aFlag ){
		boolean changed = !( aFlag == connected );
		connected = aFlag;
		if( changed ) repaint();
	}

	public void removeAllPoints(){
		size = 0;
		repaint();
		rectangle = DRectangle.getEmpty();
	}

	public String toString(){
		String text = "dPointSet[size:"+size;
		for( int i=0; i<size; i++ )
			text += ",("+x[i]+","+y[i]+")";
		text += "]";
		return text;
	}
}


