package wonderlab.graphics.geometry;
import wonderlab.graphics.geometry.Vertex;
import wonderlab.graphics.shape.*;
import java.util.LinkedList;
import java.util.Iterator;
import java.util.ListIterator;

public class Polygon {

	LinkedList vertices;
	
	int size;
	
	public Polygon() {
	
		vertices = new LinkedList();
		
	}
	
	public Vertex getVertex(int i) {
	
		return (Vertex)vertices.get(i);
		
	}

	public Vertex get(int i) {
	
		return getVertex(i);
		
	}
	
	public void add( Vertex p ) {
	
		vertices.addLast(p);
		
	}
	
	public int size() {
		size = vertices.size();
		return size;
	}
	
	public Polygon[] asTriangles() {
	
		Polygon[] triangles = null;
		if (size() < 3) {
			System.out.println("asTriangles failed, polygon has only " + size + " (i.e. < 3) vertices."); 
		} else if (size() == 3) {
			triangles = new Polygon[1];
			triangles[0] = this;
		} else {
			triangles = new Polygon[size()];
			Vertex c = centroid();	
			int j = 0;
			while (j < (size - 1)) {
	
				triangles[j] = new Polygon();
				triangles[j].add(c);
				triangles[j].add((Vertex)vertices.get(j));
				triangles[j].add((Vertex)vertices.get(j+1));
				j++;
			}
			triangles[j] = new Polygon();
			triangles[j].add(c);
			triangles[j].add((Vertex)vertices.getLast());
			triangles[j].add((Vertex)vertices.getFirst());
		}
		return triangles;
	}
	
	public Vertex centroid() {
			
		Vertex c = new Vertex();
		Vertex temp = null;
		
		size();
		for (int j = 0; j < size; j++) {
			temp = (Vertex)vertices.get(j);
			c.add((Vertex)vertices.get(j));
		}

		c.pos().scaleBy((float)1./size());
		c.normal().scaleBy((float)1./size());
		c.normal().normalize();
		c.color().scaleBy((float)1./size());
		
		// copy material from last vertex
		// this is probably a bad idea.  Probably want to get the material directly from the shape...
		if (temp !=null) {
			c.setMaterial(temp.material());
		}	
		return c;
		
	}
	
	public void transform(Matrix3D T, Matrix3D N) {

		//T.print();
		Vertex v;
		for (int i = 0; i < vertices.size(); i++) {
			v = (Vertex)vertices.get(i);
		}
	}	

	public void print() {
		
		System.out.println("Polygon ID " + this + " printing...");
		System.out.println("I have " + size() + " vertices.");

		Iterator i = vertices.listIterator(0);
		
		int j = 0;
		String s;
		
		Vertex temp;
		while (i.hasNext()) {
			temp = (Vertex)vertices.get(j);
			temp.print();
			i.next();
			j++;
		}

		System.out.println("Finished printing...");
	}
}
		
		
			