/* Jungle Monkey
 * Copyright (C) 1999-2001  The Regents of the University of Michigan
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <glib.h>
#include <gnet/gnet.h>
#include <unistd.h>
#include <stdio.h>

#include "sha_async.h"

static int failed = 0;
#define TEST(S, C) do {                             \
if (C) { g_print ("%s: PASS\n", (S));         }     \
else   { g_print ("%s: FAIL\n", (S)); failed = 1; } \
} while (0)


#define NUM_ASYNC 32
#define FILENAME  "file1"
#define STR	  "hello world\n"
#define STRLEN	  12
#define NUMSTR	  10000

static void  sha_cb (GSHA* sha, gpointer user_data);

static GSHA*	    good_sha;
static GSHAAsyncID* ids[NUM_ASYNC];


int
main (int argc, char* argv[])
{
  FILE* file;
  int i;
  GMainLoop* main_loop;

  /* Create temp file */
  file = fopen (FILENAME, "w"); 
  g_assert (file);
  for (i = 0; i < NUMSTR; ++i)
    fwrite (STR, STRLEN, 1, file);
  fclose (file);

  /* Create good sha */
  good_sha = gnet_sha_new_incremental ();
  for (i = 0; i < NUMSTR; ++i)
    gnet_sha_update (good_sha, STR, STRLEN);
  gnet_sha_final (good_sha);

  /* Start some async calcs */
  for (i = 0; i < NUM_ASYNC; ++i)
    ids[i] = gnet_sha_new_file_async (FILENAME, sha_cb, (gpointer) i);

  /* Start loop */
  main_loop = g_main_new(FALSE);
  g_main_run(main_loop);

  exit (0);
}



static void 
sha_cb (GSHA* sha, gpointer user_data)
{
  static int count = NUM_ASYNC;
  gint num = (gint) user_data;

  TEST ("sha correct",  gnet_sha_equal (sha, good_sha));

  g_print ("sha %d done\n", num);

  gnet_sha_delete (sha);

  /* First one done cancels the second and 17th one */
  if (ids[2]) 
    {
      gnet_sha_new_file_async_cancel (ids[2]);
      ids[2] = NULL;
      --count;
    }
  if (ids[17])
    {
      gnet_sha_new_file_async_cancel (ids[17]);
      ids[17] = NULL;
      --count;
    }

  if (--count == 0)
    {
      unlink (FILENAME);
      exit (failed);
    }
}


syntax highlighted by Code2HTML, v. 0.9.1