import Jcg.geometry.Point_2;
import Jcg.mesh.MeshLoader;
import Jcg.pointLocation.PlanarPointLocation;
import Jcg.polyhedron.Face;
import Jcg.polyhedron.Halfedge;
import Jcg.polyhedron.Polyhedron_3;
import Jcg.viewer.old.Fenetre;

public class TestPointLocation {

    /**
     * Load a plane triangulation from an OFF file
     */    
    private static Polyhedron_3<Point_2> openTriangulation(String filename) {
    	MeshLoader loader=new MeshLoader();
    	Polyhedron_3<Point_2> planarGraph=
    		loader.getPlanarMesh(filename);

    	//System.out.println(planarGraph.verticesToString());   	
    	//System.out.println(planarGraph.facesToString());
    	//planarGraph.isValid(false);
    	return planarGraph;
    }

    /**
     * Main testing function.
     */    
    public static void main (String[] args) {
    	System.out.println("Testing point location in planar triangulations");
    	// Load a plane triangulation from an OFF file
    	Polyhedron_3<Point_2> triangulation=openTriangulation("data/delaunay100.off");
    	Face<Point_2> outerFace=triangulation.facets.get(0);
    	Halfedge<Point_2> rootEdge=outerFace.getEdge();
    	triangulation.makeHole(rootEdge); // delete the outer face
    	triangulation.isValid(false);
    	triangulation.resetMeshIndices(); // assign integer indices to vertices, half-edges and faces
    	
    	// visualize the result
    	Fenetre f=new Fenetre();
    	f.addPolyhedronEdges(triangulation);
    	
    	// Select the query point at random inside a face of the triangulation
    	Point_2 queryPoint=PointLocationInTriangulations.getRandomPoint(triangulation);
    	System.out.println("Input query point: "+queryPoint);
    	
    	// Main computation: locate the face containing the query point
    	System.out.println("Running algorithm for point location");
    	PlanarPointLocation location=new PointLocationInTriangulations();
    	Halfedge<Point_2> lastEdge=location.locatePoint(triangulation, queryPoint);
    	
    	if(lastEdge==null) {
    		System.out.println("Error: the query point has not been located");
    	}
    	else
    		System.out.println("The query point is located in face f"+lastEdge.getFace().index);
    	
    	f.addPoint(queryPoint);    	
    	f.addFatSegment((Point_2)lastEdge.getVertex().getPoint(),
    					(Point_2)lastEdge.getOpposite().getVertex().getPoint());
    	f.addFatSegment((Point_2)lastEdge.getNext().getVertex().getPoint(),
    					(Point_2)lastEdge.getNext().getOpposite().getVertex().getPoint());
    	f.addFatSegment((Point_2)lastEdge.getPrev().getVertex().getPoint(),
    					(Point_2)lastEdge.getPrev().getOpposite().getVertex().getPoint());
    }

}
