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

#include <libsoup/soup.h>

SoupSession *session;

GFileOutputStream *ostream;

gboolean unpause_msg (SoupMessage *msg)
{
  g_warning("unpausing msg");
  soup_session_unpause_message (session, msg);
  return FALSE;
}

void got_headers (SoupMessage *msg, gpointer data)
{
  g_warning("headers [%s]", soup_message_headers_get_content_type (msg->response_headers, NULL));
  g_warning("pausing msg");
  soup_session_pause_message (session, msg);
  g_timeout_add(2000, unpause_msg, msg);
}

void content_sniffed(SoupMessage *msg, const char *content_type)
{
  g_warning("sniffed: %s", content_type);
  g_warning("pausing msg");
  soup_session_pause_message (session, msg);
  g_timeout_add(2000, unpause_msg, msg);
}

void got_chunk (SoupMessage *msg, SoupBuffer *chunk, gpointer data)
{
  g_warning("got-chunk: %d", chunk->length);
  g_output_stream_write_all(G_OUTPUT_STREAM(ostream), chunk->data, chunk->length, NULL, NULL, NULL);
}

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

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

  g_thread_init (NULL);
  g_type_init ();

  GFile *file = g_file_new_for_path("/tmp/blah");
  ostream = g_file_append_to(file, G_FILE_CREATE_REPLACE_DESTINATION, NULL, NULL);

  loop = g_main_loop_new (NULL, TRUE);

  session = soup_session_async_new();
  sniffer = soup_content_sniffer_new();
  soup_session_add_feature(session, SOUP_SESSION_FEATURE(sniffer));

  /* msg = soup_message_new ("GET", "http://ad.accelerator-media.com/st?ad_type=iframe&ad_size=160x600&section=388433&IASH=OPPER"); */
  msg = soup_message_new ("GET", "http://kov.eti.br/~kov/bleh");

  g_signal_connect (msg, "got-headers", G_CALLBACK(got_headers), NULL);
  g_signal_connect (msg, "content-sniffed", G_CALLBACK(content_sniffed), NULL);
  g_signal_connect (msg, "got-chunk", G_CALLBACK(got_chunk), NULL);
  g_signal_connect (msg, "finished", G_CALLBACK(finished), loop);

  soup_session_queue_message (session, msg, NULL, NULL);

  g_main_loop_run (loop);

  return 0;
}
