#include <fstream>

#include <commandline.h>
#include <gobj.h>
#include <graphmisc.h>
#include <planeinttest.h>
#include <planepointsurface.h>
#include <pointsurface.h>
#include <zpr.h>


void planeinttestdisplay01()
{
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  gobj::global->draw();

  glerrordisplay();
  
  glutSwapBuffers();
}

void planeinttestkeyboard01(unsigned char key, int x, int y)
{
  switch (key)
  {
    case 27:
      exit(0);
      break;
  }
}

void planeinttest::test01(int & argc, char** argv)
{
  commandline cmd(argc,argv);

  string in;

  cmd.mapvar(in,"in");
  if ( in.empty() )
  {
    cout << "error: in=filename expected" << endl;
    return;
  }

  ifstream filein(in.c_str());
  assert(filein.good()==true);
  if (filein.good()==false)
    return;

  point3<double> nml;
  double d;

  filein >> nml.x;
  filein >> nml.y;
  filein >> nml.z;
  filein >> d;

  plane P1(nml,d);

  filein >> nml.x;
  filein >> nml.y;
  filein >> nml.z;
  filein >> d;

  plane P2(nml,d);

  //cout << SHOW(nml) << endl;
  //cout << SHOW(d) << endl;
  
  point3<double> A;
  point3<double> B;

  bool res = P1.intersects(A,B,P2);
  cout << SHOW(res) << endl;
    

  glutInit(&argc,argv);
  glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
  glutInitWindowSize(800,600);
  glutCreateWindow("");
  glutDisplayFunc(planeinttestdisplay01);
  glutKeyboardFunc(planeinttestkeyboard01);

  OpenGLinitialisation();

  glEnable(GL_DEPTH_TEST);
  glEnable(GL_CULL_FACE);
  glEnable(GL_NORMALIZE);

  /** Mouse interaction. */
  zpr zz;

  xGraphics.set();

  planepointsurface f1(P1);
  pointsurface<> ps1(4000);
  ps1.pre.push(new gobjglColor3ub(184,134,11) );
  ps1.addsurface2D(f1);
  gobjpush(&ps1);

  planepointsurface f2(P2);
  pointsurface<> ps2(4000);

  f2.scaleSet(100.0);

  ps2.pre.push(new gobjglColor3ub(192,192,192) );
  ps2.addsurface2D(f2);
  gobjpush(&ps2);

  gobjpush(new gobjglDisable(GL_LIGHTING));

  gobjpush(new gobjglColor3ub(255,0,0) );
  gobjpush(new gobjglBegin(GL_LINES));

  gobjpush(new gobjglVertex3d(A+B*(-10.0)));
  gobjpush(new gobjglVertex3d(A+B*10.0));

  gobjpush(new gobjglEnd() );

  zz.update();
  glutMainLoop();
}



