package math.equation;

import java.util.Scanner;

import math.geometry.Point;
import math.matrix.Vector;

public class ParametricLine {

	private Vector position;
	private Vector direction;
	
	public ParametricLine(double x0, double y0, double x1, double y1){
		newInstance(x0, y0, x1, y1);
	}
	
	public ParametricLine(Point p0, Point p1){
		Vector position = new Vector(p0);
		Vector direction = new Vector(p1).minus(position);
		newInstance(position, direction);
	}
	
	public ParametricLine(Polynomial y) throws IllegalArgumentException{
		if(y.degree() > 1) throw new IllegalArgumentException();
		newInstance(0, y.evaluate(0), 1, y.evaluate(1));
	}
	
	public ParametricLine(double x){
		newInstance(x, 0, x, 1);
	}
	
	private void newInstance(double x0, double y0, double x1, double y1){
		Vector position = new Vector(x0, y0);
		Vector direction = new Vector(x1, y1).minus(position);
		newInstance(position, direction);
	}
	
	private void newInstance(Vector position, Vector direction){
		this.position = position;
		this.direction = direction;
	}
	
	public Polynomial get(int i){
		Polynomial poly = new Polynomial(direction.get(i), position.get(i));
		poly.setSymbolic("t");
		return poly;
	}
	
	public Polynomial get(int i, String symbolic){
		Polynomial poly = get(i);
		poly.setSymbolic(symbolic);
		return poly;
	}

	@Override
	public String toString(){
		int i = 0;
		StringBuffer output = new StringBuffer();
		Scanner scannerP = new Scanner(position.toString());
		Scanner scannerD = new Scanner(direction.toString());
		String lineP, lineD;
		while(scannerP.hasNextLine()) {
			lineP = scannerP.nextLine();
			lineD = scannerD.nextLine();
			if(i==((int)(position.n()/2)+2))
				output.append("r = " + lineP + " + λ" + lineD + "\n");
			else output.append("    " + lineP + "    " + lineD + "\n");
			i++;
		}
		scannerP.close();
		scannerD.close();
		return new String(output);
	}
	
    /**
     * test client
     * @param args
     */
    public static void main(String[] args) {
    	Polynomial y = new Polynomial(4, -11.);
    	ParametricLine pl0 = new ParametricLine(y);
    	Polynomial xt = pl0.get(0);
    	Polynomial yt = pl0.get(1);
    	System.out.println("f(x) = " + y);
    	System.out.println("2D" + pl0);
    	System.out.println("x(t) " + xt);
    	System.out.println("y(t) " + yt);
    	
    	System.out.println();
    	Polynomial y1 = new Polynomial(2.);
    	ParametricLine pl1 = new ParametricLine(y1);
    	System.out.println("f(x) = " + y1);
    	System.out.println("2D" + pl1);
    	
    	double x = 2;
    	ParametricLine pl2 = new ParametricLine(x);
    	System.out.println("x = " + x);
    	System.out.println("2D" + pl2);
    	
    	Point p0 = new Point(4,-6,3);
    	Point q = new Point(-4,1,4);
    	System.out.println("P0 = " + p0 + ", Q = " + q);
    	ParametricLine pl3 = new ParametricLine(p0,q);
    	System.out.println("3D" + pl3);
    }
}
