#include <string.h>
#include <glib.h>
#include <libosso.h>
#include <libebook/e-book.h>
#include <libosso-abook/osso-abook.h>

GMainLoop *loop;

guint run_count= 0;

static void
commit_cb (EBook       *book,
                              EBookStatus  status,
                              gpointer     user_data)
{
  g_print("status: %d\n", status);
  run_count--;
  if (run_count == 0)
    g_main_loop_quit(loop);
}


static void
aggregator_ready_cb (OssoABookWaitable *aggregator,
                     const GError      *error_in,
                     gpointer           user_data)
{
    GList *master_contacts;
    GList *l;


    if (error_in) {
        g_printerr ("Error while waiting for the aggregator to be ready: "
                "%s\n", error_in->message);
        g_main_loop_quit (loop);
        return;
    }

    run_count++;

    master_contacts = osso_abook_aggregator_list_master_contacts (
        OSSO_ABOOK_AGGREGATOR (aggregator));

    for (l = master_contacts; l; l = l->next) {
        OssoABookContact *c = l->data;
	GList *attributes, *v;

	attributes = osso_abook_contact_get_attributes (E_CONTACT(c), "X-JABBER");

	if (attributes) {
	  for (v = attributes; v; v=v->next) {
	    EVCardAttribute *attr = v->data;
	    gchar *val = e_vcard_attribute_get_value (attr);

	    if (!strcmp("@chat.facebook.com", val + (strlen(val) - strlen("@chat.facebook.com")))) {
	      g_print(" X-JABBER %s: %s\n",
		      osso_abook_contact_get_display_name(c),
		      val);
	      e_vcard_remove_attribute (E_VCARD(c), attr);
	      run_count++;
	      osso_abook_contact_async_commit(c, NULL, commit_cb, NULL);
	    }
	  }
	}
    }


    g_list_free (master_contacts);

    run_count--;
    if (run_count == 0)
      g_main_loop_quit(loop);
}

int
main (int    argc,
      char **argv)
{
    osso_context_t *osso_cxt;
    OssoABookRoster *aggregator;
    GError *error = NULL;

    osso_cxt = osso_initialize (argv[0], "0.1", FALSE, NULL);
    osso_abook_init (&argc, &argv, osso_cxt);

    aggregator = osso_abook_aggregator_get_default (&error);
    if (!aggregator) {
        g_printerr ("Error getting the aggregator: %s\n",
            error ? error->message : "unknown error");
        return 1;
    }

    loop = g_main_loop_new (NULL, FALSE);

    osso_abook_waitable_call_when_ready (OSSO_ABOOK_WAITABLE (aggregator),
        aggregator_ready_cb, NULL, NULL);

    g_main_loop_run (loop);

    return 0;
}
