#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdio.h>
#include <libsoup/soup.h>

SoupSession *session;

void started (SoupSession *session, SoupMessage *msg, SoupSocket *socket, gpointer data)
{
  SoupMessageHeadersIter iter;
  const char *name;
  const char *value;

  g_warning("request headers");
  soup_message_headers_iter_init (&iter, msg->request_headers);
  while (soup_message_headers_iter_next (&iter, &name, &value))
    printf("%s: %s\n", name, value);
}

void got_headers (SoupMessage *msg, gpointer data)
{
  SoupMessageHeadersIter iter;
  const char *name;
  const char *value;

  g_warning("response headers");
  soup_message_headers_iter_init (&iter, msg->response_headers);
  while (soup_message_headers_iter_next (&iter, &name, &value))
    printf("%s: %s\n", name, value);
}

void restarted (SoupMessage *msg, gpointer data)
{
  g_warning("restarted");
}

void got_chunk (SoupMessage *msg, SoupBuffer *chunk, gpointer data)
{
  GString *string = g_string_new_len (chunk->data, chunk->length);
  gchar *escaped_string = g_strescape (string->str, NULL);
  g_warning("got-chunk: %s", escaped_string);
  g_string_free (string, TRUE);
  g_free (escaped_string);
}

void finished (SoupSession *session, SoupMessage *msg, GMainLoop *loop)
{
  g_warning("finished");
  g_main_loop_quit (loop);
}

int main (int argc, char **argv)
{
  SoupMessage *msg;
  GMainLoop *loop;

  g_thread_init (NULL);
  g_type_init ();

  loop = g_main_loop_new (NULL, TRUE);

  session = soup_session_async_new();
  g_signal_connect (session, "request-started", G_CALLBACK(started), NULL);

  msg = soup_message_new ("GET", "https://webaloe.ulima.edu.pe/portalUL/");

  g_signal_connect (msg, "got-headers", G_CALLBACK(got_headers), NULL);
  g_signal_connect (msg, "got-chunk", G_CALLBACK(got_chunk), NULL);
  g_signal_connect (msg, "restarted", G_CALLBACK(restarted), NULL);

  soup_session_queue_message (session, msg, (SoupSessionCallback)finished, loop);

  g_main_loop_run (loop);

  return 0;
}
