#include "ev_dispatch.h"
#include "ev_http.h"

using namespace EVD;


// catch SIGINT to kill process 
static void  SIGINT_handler(int sig)
{
  exit(sig);
}

static void run_tests( Dispatch &dispatcher, int count )
{
  struct timeval start_time;
  Timer::current_time(&start_time);
  int response_count = 0;

  dispatcher.request( new HttpRequest( dispatcher, "http://127.0.0.1:4044/bytes/10200/" ) );
  dispatcher.request( new HttpRequest( dispatcher, "http://127.0.0.1:4044/bytes/10080/" ) );
  dispatcher.request( new HttpRequest( dispatcher, "http://127.0.0.1:4044/delay/0.2/" ) );
  dispatcher.request( new HttpRequest( dispatcher, "http://127.0.0.1:4044/bytes/100900/" ) );
  dispatcher.request( new HttpRequest( dispatcher, "http://127.0.0.1:4044/delay/0.1/" ) );
  dispatcher.request( new HttpRequest( dispatcher, "http://127.0.0.1:4044/delay/0.1/" ) );
  dispatcher.request( new HttpRequest( dispatcher, "http://127.0.0.1:4044/delay/0.3/" ) );
  dispatcher.request( new HttpRequest( dispatcher, "http://127.0.0.1:4044/bytes/1010/" ) );
  int expected_response_count = 8 ;

  //ev_sleep(0.2);

  Response *rep = NULL;
  double longest_request = 0.0;

  // timer issues
  Timer timeout(1,(500*1000*1000));

  while( expected_response_count > 0 && (rep = dispatcher.get_next_response(timeout)) ){
    if( longest_request < rep->response_time ){
      longest_request = rep->response_time;
    }
    printf( "recieved response(%d): from '%s', Content-Length: %d bytes, within: %.5lf seconds \n", rep->id, rep->name.c_str(), rep->body.length(), rep->response_time );
    ++response_count;
    delete rep;
    --expected_response_count;
  }
  
  if( expected_response_count != 0 ){
    printf( "Expected: %d responses but recieved: %d\n", expected_response_count, response_count );
  }
  printf( "%d responses completed, within %.5lf seconds\n", response_count, Timer::elapsed_time( &start_time ) );
  printf( "longest request: %.5lf\n", longest_request );
}

int main(int argc, char **argv)
{
  Dispatch dispatcher;

  if (signal(SIGINT, SIGINT_handler) == SIG_ERR) {
    printf("SIGINT install error\n");
    exit(1);
  }

  if( !dispatcher.start() ){
    fprintf( stderr, "Failed to start up dispatcher\n" );
    return 1;
  }

  printf( "dispatcher thread running...\n" );

  struct timeval start_time;
  Timer::current_time(&start_time);

  run_tests( dispatcher, 10 );
  run_tests( dispatcher, 10 );
  run_tests( dispatcher, 10 );
  run_tests( dispatcher, 10 );

  printf( "total time: %.5lf seconds\n", Timer::elapsed_time( &start_time ) );

  dispatcher.stop();

  return 0;
}