#include <stdio.h>

#ifdef BUILD_IN_OOO
#include "EApi.h"
#else
#include "libebook/e-book.h"
#endif

int
main (int argc, char **argv)
{
  ESourceList *source_list;
  EContactField fld;
  EBookQuery *query;
  char *s;
  GSList *group;
  GError *error = NULL;
  
  if (argc != 3)
    fprintf (stderr, "Usage: %s field value\n",
	     g_path_get_basename (argv[0])),
      exit (1);
  
  fld = e_contact_field_id (argv[1]);
  query = e_book_query_field_test (fld, E_BOOK_QUERY_IS, argv[2]);
  
  s = e_book_query_to_string (query);
  printf ("Query sexp: %s\n", s);
  
  if (!e_book_get_addressbooks (&source_list, &error))
    fprintf (stderr, "Couldn't get list of addressbooks: %s\n", error->message),
      exit (1);
  
  for (group = e_source_list_peek_groups (source_list); group; group = group->next)
    {
      GSList *source;
      
      for (source = e_source_group_peek_sources (E_SOURCE_GROUP (group->data)); source; source = source->next)
	{
	  EBook *book;
	  GList *contacts;
	  GList *contact;

	  book = e_book_new (E_SOURCE (source->data), &error);
	  if (!book)
	    {
	      fprintf (stderr, "Could not open get addressbook %s: %s\n",
		       e_source_get_uri (E_SOURCE (source->data)), error->message);
	      error = NULL;
	      continue;
	    }
	  
	  if (!e_book_open (book, TRUE, &error))
	    {
	      fprintf (stderr, "Could not open addressbook %s: %s\n",
		       e_book_get_uri (book), error->message);
	      error = NULL;
	      continue;
	    }
	  
	  if (!e_book_get_contacts (book, query, &contacts, NULL))
	    {
	      fprintf (stderr, "Could not search book %s: %s\n",
		       e_book_get_uri (book), error->message);
	      error = NULL;
	      continue;
	    }

	  printf ("Searched addressbook %s: got %d %s:\n",
		  e_book_get_uri (book), g_list_length (contacts),
		  g_list_length (contact) == 1 ? "entry" : "entries");

	  for (contact = contacts; contact; contact = contact->next)
	    {
	      printf ("  %s: %s (%s %s)\n",
		      (char *) e_contact_get (E_CONTACT (contact->data), E_CONTACT_UID),
		      (char *) e_contact_get (E_CONTACT (contact->data), E_CONTACT_FULL_NAME),
		      (char *) e_contact_get (E_CONTACT (contact->data), E_CONTACT_GIVEN_NAME),
		      (char *) e_contact_get (E_CONTACT (contact->data), E_CONTACT_FAMILY_NAME));
	    }
	}
    }
  return 0;
}
