#include <CGAL/Cartesian.h>
#include <CGAL/Point_2.h>
#include <CGAL/Delaunay_triangulation_2.h>
#include <CGAL/IO/Qt_widget_Delaunay_triangulation_2.h>
#include <CGAL/IO/Qt_widget.h>
#include <CGAL/IO/Qt_widget_layer.h>
#include <qapplication.h>

typedef CGAL::Cartesian<double>		    Rep;
typedef CGAL::Point_2<Rep>		    Point;
typedef CGAL::Delaunay_triangulation_2<Rep> Delaunay;


typedef CGAL::Triangle_2<Rep>		    Triangle;
typedef Delaunay::Vertex_handle             Vertex;
typedef Delaunay::Face_handle               Face;

/////////////////////////////////////////////////////////
//  Les objets affiches sont declares ici en variable globales
//  l'affichage est fait dans la methode "draw" ci dessous

Delaunay dt;
Point    the_point = Point(-1,-1);
Vertex   voisin;
Face     face_trouvee;
Triangle triang;

class My_layer : public CGAL::Qt_widget_layer{
  void draw(){

    // affichage triangulation et point clique
    *widget << CGAL::LineWidth(3) << CGAL::noFill << CGAL::RED << dt 
	    << CGAL::PointSize(6) << CGAL::BLUE << the_point 
      ;

    // affichage triangle
    if (face_trouvee != Face() &&   ! dt.is_infinite(face_trouvee) )
      *widget  <<  CGAL::ORANGE << triang ;

    // affichage plus proche voisin
    if (voisin != Vertex() ) 
       *widget << CGAL::GREEN << voisin->point();
  }
};

class My_window : public CGAL::Qt_widget {
public:
  My_window(int x, int y)
  {
    resize(x,y);
    attach(&layer);
  };
private:
  //this method is called when the user presses the mouse
  void mousePressEvent(QMouseEvent *e)
  {
    Qt_widget::mousePressEvent(e);

    /////////////////////////////////////////////////////////////
    //  C'EST ICI QUE CA SE PASSE QUAND ON CLIQUE !
    //
    if (e->button() == Qt::LeftButton) {
      dt.insert(Point(x_real(e->x()), y_real(e->y())));
    }
    if (e->button() == Qt::MidButton) {
      face_trouvee = dt.locate(Point(x_real(e->x()), y_real(e->y())));
      triang = Triangle(face_trouvee->vertex(0)->point(),
		      face_trouvee->vertex(1)->point(),
		      face_trouvee->vertex(2)->point());
    }
    if (e->button() == Qt::RightButton) {
      the_point =  Point(x_real(e->x()), y_real(e->y()));
      voisin = dt.nearest_vertex( the_point) ;
    }
    /////////////////////////////////////////////////////////////

    redraw();
  }
  My_layer layer;
};

int main( int argc, char **argv )
{
    QApplication app( argc, argv );
    My_window *W = new My_window(400,400);
    app.setMainWidget(W);
    W->show();
    W->set_window(0, 400, 0, 400);
    return app.exec();
}

