// Vorosweep - Copyright (C) 2010-2014 T. Mouton
//
// See the LICENSE.txt file for license information. Please report all
// bugs and problems to <thibaud.mouton@gmail.com>.

#include "vorosweep.h"

using namespace vorosweep;

void Graph::export_vtk ( const char *name, bool flat )
{
  if (!(int)pointlist.size() || !(int)indexmap.size()  )
  {
    printf("--> You have to call generate_internals before exporting\n");
    return;
  }
    
  char filename[100];
  static int count = 0;
  sprintf ( filename, "%s_%d.vtk", name, count++ );

  tprintf ( "Writing file %s ...\n", filename );
  FILE *fp_rw = fopen ( filename, "w" );

  fprintf ( fp_rw, "# vtk DataFile Version 2.0\n" );
  fprintf ( fp_rw, "Really cool data\n" );
  fprintf ( fp_rw, "ASCII\n" );
  fprintf ( fp_rw, "DATASET POLYDATA\n" );

  fprintf ( fp_rw, "POINTS %d float\n", ( int ) pointlist.size() );
  for ( int i = 0; i < ( int ) pointlist.size(); i++ )
  {
    Point *pt = pointlist[i];
    if (!flat)
      fprintf ( fp_rw, "%lf %lf %lf\n", pt->p[0], pt->p[1], pt->p[2] );
    else
      fprintf ( fp_rw, "%lf %lf %lf\n", pt->p[0], pt->p[1], 0.0 );    
  }

  fprintf ( fp_rw, "POLYGONS %d %d\n", nbf, nbvf );
  for ( int i = 0; i < ( int ) generatorlist.size(); i++ )
  {
    Convex_generator *cg = generatorlist[i];
    if ( cg->is_active() )
    {
      for ( int j = 0; j < cg->face_size(); j++ )
      {
        SweepFacet *sf = cg->get_sweepfacet ( j );
        FrontLine *fl = sf->get_frontline ( );
        std::list<Polygon *> plist = fl->get_polygons();
        for ( std::list<Polygon *>::iterator itp = plist.begin(); itp != plist.end(); itp++ )
        {
          Polygon *pol = *itp;
          fprintf ( fp_rw, "%d", pol->get_point_size() );
          std::list<Point *> vlist = pol->get_points();
          for ( std::list<Point *>::iterator itv = vlist.begin(); itv != vlist.end(); itv++ )
          {
            Point *pt = *itv;
            itindex = indexmap.find ( pt );
            fprintf ( fp_rw, " %d", itindex->second );
          }
          fprintf ( fp_rw, "\n" );
        }
      }
    }
  }
  
  fprintf ( fp_rw, "CELL_DATA %d\n", nbf );
  fprintf ( fp_rw, "SCALARS index int 1\n" );
  fprintf ( fp_rw, "LOOKUP_TABLE default\n" );
  int idgen = 0;
  for ( int i = 0; i < ( int ) generatorlist.size(); i++ )
  {
    Convex_generator *cg = generatorlist[i];
    if ( cg->is_active() )
    {
      for ( int j = 0; j < cg->face_size(); j++ )
      {
        fprintf ( fp_rw, "%d\n", idgen );
      }
      idgen++;
    }
  }

  fclose ( fp_rw );
  tprintf ( "Done\n" );
}
