/* gcc -Wall $(pkg-config --cflags --libs libebook-1.2) e-client.c -o e-client */

#include <stdlib.h>
#include <string.h>
#include <libedataserver/e-account.h>
#include <libedataserver/e-source.h>
#include <gio/gio.h>
#include <libebook/e-book-client.h>


EBookClient *addressbook; 

static void callback (GObject* source_object, GAsyncResult* _res_, gpointer _user_data_) {
  GError *error = NULL;

  e_client_open_finish ((EClient*) addressbook, _res_, &error);

  /* BUG: error will be set here.. "Opening Book in Progress" */
}

static ESource * get_source (void)
{
  ESourceGroup* group = NULL;
  ESource* source = NULL;
  GError *error = NULL;
  ESourceList* sl = NULL;

  group = e_source_group_new ("Test", "local:");
  source = e_source_new_with_absolute_uri ("Test", "local:///tmp/test");

  return source;
}

static void
client_opened_cb (EClient *client, GError *error)
{
  if (error == NULL) {
    if (e_client_is_opened ((EClient *)addressbook)) {
      printf ("Yes\n");
    } else {
      printf ("No\n");
    }
  } else {
    printf ("Error: %s\n", error->message);
  }

  exit (-1);
}

int main (int argc, char **argv)
{
  GMainLoop *loop;
  GError *error = NULL;
  ESource *source;

  g_type_init ();

  source = get_source ();
  addressbook = e_book_client_new (source, &error);

  if (error == NULL) {
    g_signal_connect ((EClient*) addressbook,
		      "opened", G_CALLBACK (client_opened_cb),
		      NULL);
    e_client_open ((EClient*) addressbook, FALSE, NULL, callback, NULL);

    loop = g_main_loop_new (NULL, FALSE);
    g_main_loop_run (loop);
    g_main_loop_unref (loop);
  } else {
    printf ("Error with e_book_client_new: %s\n", error->message);
  }

  return 0;
}
