/* gcc $(pkg-config --cflags --libs libgdata goa-1.0 gio-2.0 glib-2.0)
   gdata-query.c */

#include <gio/gio.h>
#include <glib.h>

#define GOA_API_IS_SUBJECT_TO_CHANGE
#include <gdata/gdata.h>
#include <goa/goa.h>

gint
main (void)
{
  GDataDocumentsFeed *feed = NULL;
  GDataDocumentsQuery *query = NULL;
  GDataDocumentsService *service = NULL;
  GError *error = NULL;
  GList *accounts = NULL;
  GList *entries;
  GList *l;
  GoaClient *client = NULL;

  client = goa_client_new_sync (NULL, &error);
  if (error != NULL)
    {
      g_warning ("%s", error->message);
      g_error_free (error);
      goto out;
    }

  accounts = goa_client_get_accounts (client);
  for (l = accounts; l != NULL; l = l->next)
    {
      GoaAccount *account;
      GoaObject *object = GOA_OBJECT (l->data);
      const gchar *account_identity;
      const gchar *provider_type;

      account = goa_object_peek_account (object);
      account_identity = goa_account_get_identity (account);
      provider_type = goa_account_get_provider_type (account);

      if (g_strcmp0 (provider_type, "google") == 0)
        {
          GDataGoaAuthorizer *authorizer;

          authorizer = gdata_goa_authorizer_new (object);
          service = gdata_documents_service_new (GDATA_AUTHORIZER (authorizer));
          g_object_unref (authorizer);
        }
    }

  if (service == NULL)
    {
      g_warning ("account not found");
      goto out;
    }

  query = gdata_documents_query_new_with_limits (NULL, 1, 5);
  gdata_documents_query_set_show_folders (query, TRUE);

  while (TRUE)
    {
      feed = gdata_documents_service_query_documents (service, query, NULL, NULL, NULL, &error);
      if (error != NULL)
        {
          g_warning ("%s", error->message);
          g_error_free (error);
          goto out;
        }

      entries = gdata_feed_get_entries (GDATA_FEED (feed));
      if (entries == NULL)
        goto out;

      for (l = entries; l != NULL; l = l->next)
        {
          GDataEntry *entry = GDATA_ENTRY (l->data);
          const gchar *title;

          title = gdata_entry_get_title (entry);
          g_message ("%s", title);
        }

      gdata_query_next_page (GDATA_QUERY (query));
      g_object_unref (feed);
    }

 out:
  g_clear_object (&feed);
  g_clear_object (&query);
  g_clear_object (&service);
  g_clear_object (&client);
  g_list_free_full (accounts, g_object_unref);
  return 0;
}
