#include <libgnomevfs/gnome-vfs.h>
#include <glib.h>
#include <stdio.h>
#include <stdlib.h>

int print_error(GnomeVFSResult result, const char *uri_string);

static int
update_transfer_callback (GnomeVFSAsyncHandle *handle,
               GnomeVFSXferProgressInfo *progress_info,
               gpointer data) {
               
  printf("Transupate: status = %d, phase = %d\n", progress_info->status, 
    progress_info->phase);
  return 1;
}

static int
sync_transfer_callback (GnomeVFSXferProgressInfo *progress_info, 
                        gpointer data) {
                        
  printf("Synctrans: status = %d, phase = %d\n", progress_info->status, 
    progress_info->phase);
  
  if (progress_info->phase == GNOME_VFS_XFER_PHASE_COMPLETED) {
    exit(EXIT_SUCCESS);
  }
  
  return 1;
}


int
main (int argc, char **argv) {
  GMainLoop *loop;
  GnomeVFSAsyncHandle *handle;
  GList *source_uri, *dest_uri;
  GnomeVFSURI *source, *dest;
  GnomeVFSResult result;
  gchar *s_dest;
  
  /* remember to initialize GnomeVFS! */
  if (!gnome_vfs_init ()) {
    printf ("Could not initialize GnomeVFS\n");
    exit(EXIT_FAILURE);
  }

  s_dest = g_strconcat(g_get_tmp_dir(), G_DIR_SEPARATOR_S, "test.txt", NULL);
  
  source = gnome_vfs_uri_new("http://www.icecrew.nl/nonexistent.txt");
  dest = gnome_vfs_uri_new(s_dest);

  g_free(s_dest);
  
  /* Add it twice to show it says it completes after the first one fails */
  source_uri = g_list_append(NULL, source);
  source_uri = g_list_append(source_uri, source);
  
  dest_uri = g_list_append(NULL, dest);  
  dest_uri = g_list_append(dest_uri, dest);

  result = gnome_vfs_async_xfer(&handle, source_uri, dest_uri, 
    GNOME_VFS_XFER_DEFAULT, GNOME_VFS_XFER_ERROR_MODE_QUERY, 
    GNOME_VFS_XFER_OVERWRITE_MODE_REPLACE, GNOME_VFS_PRIORITY_DEFAULT, 
    update_transfer_callback, NULL, sync_transfer_callback, NULL);

  gnome_vfs_uri_unref(source);
  gnome_vfs_uri_unref(dest);
  
  g_list_free(source_uri);
  g_list_free(dest_uri);
  
  if (result != GNOME_VFS_OK) {
    print_error(result, NULL);  
  } else {
    loop = g_main_loop_new(NULL, TRUE);
    g_main_loop_run(loop);
    gnome_vfs_shutdown();
  }

  return 0;
}


int
print_error (GnomeVFSResult result, const char *uri_string) {
  const char *error_string;
  /* get the string corresponding to this GnomeVFSResult value */
  error_string = gnome_vfs_result_to_string (result);
  printf ("Error %s occured opening location %s\n", error_string, uri_string);
  return 1;
}
