/****************************************************************************
** GMAF - The Geometry Modeling Algorithms Framework
**
** Created : 03112000
**
** Copyright (C) 2000 by Le-Jeng Shiue.  All rights reserved.
**
****************************************************************************/
#include <assert.h>

#include "CgalExtension/cgalConfig.h"
#include <CGAL/Bbox_3.h>

#include "gmafPolyhedron.h"
#include "CgalExtension/cgalPolyhedronBuilder.cc"

#include "gmafFacetIterator.h"


gmafPolyhedron::gmafPolyhedron() 
  : gmafDataStructure() {
  mpPolyhedron = new Polyhedron;
  mpBbox = NULL;
}

gmafPolyhedron::~gmafPolyhedron() {
  if (mpPolyhedron == NULL) assert(0);
  delete mpPolyhedron;
  if (mpBbox != NULL) delete mpBbox;
}

void gmafPolyhedron::init() {
  // initVertex & initHalfedge are still empty -- don't need to execute 
  //
  //  std::for_each(mpPolyhedron->vertices_begin(), 
  //		mpPolyhedron->vertices_end(), 
  //		initVertex);

  //  std::for_each(mpPolyhedron->halfedges_begin(), 
  //		mpPolyhedron->halfedges_end(), 
  //		initHalfedge);


  std::for_each(mpPolyhedron->facets_begin(), 
		mpPolyhedron->facets_end(), 
		initFacet);

  int idx = 0;
  // set vertex index
  Vertex_iterator vitr = mpPolyhedron->vertices_begin();
  Vertex_iterator vitr_end = mpPolyhedron->vertices_end();
  while(vitr != vitr_end) {
    vitr->setIdx(idx);
    idx++; vitr++;
  }

  idx = 0;
  // set halfedge index
  Halfedge_iterator heitr = mpPolyhedron->halfedges_begin();
  Halfedge_iterator heitr_end = mpPolyhedron->halfedges_end();
  while(heitr != heitr_end) {
    heitr->setIdx(idx);
    idx++; heitr++;
  }

  idx = 0;
  // set facet index
  Facet_iterator fitr = mpPolyhedron->facets_begin();
  Facet_iterator fitr_end = mpPolyhedron->facets_end();
  while(fitr != fitr_end) {
    fitr->setIdx(idx);
    idx++; fitr++;
  }

}

void gmafPolyhedron::initFacet(Facet& f) {
  // init plane equation
  Halfedge_handle h = f.halfedge();
  f.plane() = Plane(h->opposite()->vertex()->point(), 
		    h->vertex()->point(),
		    h->next()->vertex()->point());
}

void gmafPolyhedron::initVertex(Vertex& v) {
}

void gmafPolyhedron::initHalfedge(Halfedge& he) {
}


void gmafPolyhedron::import(std::istream& in) {
  // I should check if the input data is correct... later ^_^
  cgalPolyhedronBuilder<HDS> pb(&in);
  mpPolyhedron->delegate(pb);
  
  mpBbox = new CGAL::Bbox_3(pb.mXmin, pb.mYmin, 
			    pb.mZmin, pb.mXmax, 
			    pb.mYmax, pb.mZmax);
  mCenter = Point((pb.mXmin+pb.mXmax)/2, 
		  (pb.mYmin+pb.mYmax)/2, 
		  (pb.mZmin+pb.mZmax)/2);
  
  init();

  mValid = true;
}
