// Gnurbs - A curve and surface library
// Copyright (C) 2008-2026 Eric Bechet
//
// See the LICENSE file for contributions and license information.
// Please report all bugs and problems to <bechet@cadxfem.org>.
//

#include <iostream>
#include <vector>

#include "nvtkdisplay.h"

// function that computes intersections between planes and the STL file
void slice(std::vector<triangle> &mesh,npoint3 pt,npoint3 vec,int nb,std::vector<npoint3> &pts)
{
  // to code
}


//load mesh function
void loadmesh(std::string filename,std::vector<triangle> &mesh);



int main(int argc, char * argv[])
{
  data_container data;
  nvtkdisplay display;

  std::vector<npoint3> liste; // list of intersection points
  std::vector<triangle> mesh; // la liste des points d'intersection
  if (argc==2)
  {
    loadmesh(argv[1],mesh);
  }
  else
  {
    loadmesh("mesh.stl",mesh);
  }
  
  slice(mesh,npoint3(0,0,0),npoint3(1,1,1),10,liste); // call to the function computing intersection points

  if (liste.size()!=1)
    for (int i=1;i<liste.size();++i) {line l;l.pts[0]=liste[i-1]; l.pts[1]=liste[i];data.add_line(l);}
  else
    data.add_point(liste[0]);
  for(int i=0;i<mesh.size();++i) data.add_triangle(mesh[i]);
  display.init_data(data);
  display.display();
  return 0;
}

#ifndef _WIN32
int stricmp ( const char *s1, const char*s2 )
{
  return strcasecmp ( s1,s2 );
}
#endif

//function that loads a STL file in memory (implementation)
void loadmesh(std::string filename,std::vector<triangle> &mesh)
{
  ifstream fe;
  char poub1[255];
  char poub2[255];
  long i,j;
  triangle t;
  double nx,ny,nz;
  std::cout << " Loading " << filename << " ... ";
  fe.open ( filename.c_str() );

  if ( !fe.fail() )
  {
    fe>>poub1;
    fe.getline ( poub2,255 );

    if ( stricmp ( poub1,"solid" ) ==0 )
    {

      fe >> poub1 >> poub2 >> nx >> ny >> nz ;

      while ( !fe.eof() )
      {
        if ( ( stricmp ( poub1,"endsolid" ) ==0 ) )
        {
          break;
        }

        if ( ( stricmp ( poub1,"facet" ) !=0 ) || ( strcmp ( poub2,"normal" ) !=0 ) )
        {

          fe.close();
          throw 1;
          break;
        }

        fe >> poub1 >> poub2;

        if ( ( stricmp ( poub1,"outer" ) !=0 ) )
        {
          fe.close();
          throw 1;

          break;
        }

        for ( j=0; j<3; ++j )

        {

          fe >> poub1 >> t.pts[j][0] >> t.pts[j][1] >> t.pts[j][2];
          if ( ( stricmp ( poub1,"vertex" ) !=0 ) )

          {
            fe.close();
            throw 1;
            break;
          }
        }

        mesh.push_back(t);

        fe >> poub1;
        //poub1=endloop
        fe >> poub2;
        //poub1=endfacet

        fe >> poub1 >> poub2 >> nx >> ny >> nz ; // normal vector (unused here)
      }
      fe.close();
    }
    else
    {
      fe.close();
      throw 1;
    }
  }
  else
  {
    std::cout << "File not found" << std::endl;
    throw 1;
  }
  std::cout << mesh.size()  << " triangles."  << std::endl;
}



