// 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;

// consists only in adding the facet in the buckets
void Graph::handle_facetswitch ( Event *ev )
{
  SweepFacet *sf = ev->get_sweepfacet();
  if ( sf->is_stopped() )
    return;
  double *pos = ev->get_coord();
  double time = ev->get_time();
  // we need to check if pos is still in the front of the facet
  FrontLine *fl = sf->get_frontline();
  if ( !fl->valid_event ( pos, time ) )
  {
    add_earliest_event ( sf );
    return;
  }
  
  int gid = ev->get_gid();
  
  if ( gid == -1 ) // no need to set the facet stopped
    return;
  // add mc to the newly entered cell
  dbgprintf ( 5, "--> inserting facet in cell %d\n", gid );
  // if insertion failed, facet was already in bucket
  if ( !bucketgrid->insert_sweepfacet ( sf, gid ) )
  {
    add_earliest_event ( sf );
    return;
  }
  // compute next facet switch events
  Event *eventlist[MAX_EVENT_LIST];
  int nbe = 0;
  next_facetswitch ( sf, pos, gid, eventlist, nbe );
  dbgprintf ( 5, "--> listing %d next facet switch events :\n", nbe );
  for ( int i = 0; i < nbe; i++ )
  {
    Event *next = eventlist[i];
    dbgprintf ( 5, "--> next switch event add :\n" );
    add_event ( next );
  }

  // check for potential crash events in cell gid
  process_facet_events ( sf, time, gid );

//   // check for potential crash events in cell gid
//   Bucket *buc = bucketgrid->get_bucket ( gid );
//   dbgprintf ( 2, "--> generating crash events :\n" );
//   buc->generate_facetcrash_events ( sf, get_time(), gid, econtainer, eventlist, nbe );
//   dbgprintf ( 2, "--> listing %d crash events :\n", nbe );
//   for ( int i = 0; i < nbe; i++ )
//   {
//     Event *ne = eventlist[i];
//     ne->print();
//     SweepEdge *se = ne->get_sweepedge ( 0 );
//     se->print();
//     if ( se->get_earliest_event() == ne )
//       add_event ( ne );
//   }
// //   getchar();
}
