#include <gio/gio.h>
#include <glib.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "gtlsconnection.h"

static void
ready (GObject *obj,
    GAsyncResult *result,
    gpointer user_data)
{
  GSocketClient *client = G_SOCKET_CLIENT (obj);
  GTcpConnection *connection;
  GError *error = NULL;
  GInputStream *input;
  GOutputStream *output;
  GTLSSession *sess;
  GTLSConnection *tcon;
  char buffer[2048];
  gssize bytes;

  connection = g_socket_client_connect_finish (client, result, &error);

  if (connection == NULL)
    g_error ("connect: %s: %d, %s", g_quark_to_string (error->domain), error->code, error->message);

  input = g_io_stream_get_input_stream (G_IO_STREAM (connection));
  output = g_io_stream_get_output_stream (G_IO_STREAM (connection));

  bytes = g_input_stream_read (input, buffer, sizeof buffer, NULL, NULL);
  buffer[bytes] = '\0';
  g_print ("%"G_GSSIZE_FORMAT" bytes read: %s\n", bytes, buffer);


  g_output_stream_write (output, "a starttls\n", 11, NULL, NULL);

  bytes = g_input_stream_read (input, buffer, sizeof buffer, NULL, NULL);
  buffer[bytes] = '\0';
  g_print ("%"G_GSSIZE_FORMAT" bytes read: %s\n", bytes, buffer);

  sess = g_tls_session_new (G_IO_STREAM (connection));
  tcon = g_tls_session_handshake (sess, NULL, &error);

  if (!tcon)
    g_error ("err %d %d %s\n", error->domain, error->code, error->message);

  g_debug ("awesome!!  TLS worked out.\n\n");

  input = g_io_stream_get_input_stream (G_IO_STREAM (tcon));
  output = g_io_stream_get_output_stream (G_IO_STREAM (tcon));

  g_output_stream_write (output, "a capability\n", 13, NULL, NULL);
  bytes = g_input_stream_read (input, buffer, sizeof buffer, NULL, NULL);

  buffer[bytes] = '\0';
  g_print ("%"G_GSSIZE_FORMAT" bytes read: %s\n", bytes, buffer);
}

int
main (void)
{
  GError *error = NULL;
  GTcpConnection *connection;
  GSocketClient *client;
  GInputStream *input;
  char buffer[2048];
  gssize bytes;

  g_type_init ();

  client = g_socket_client_new ();


  g_socket_client_connect_to_host_async (client, "imap2.tinymail.org",
                                         143, NULL, ready, NULL);

  g_main_loop_run (g_main_loop_new (NULL, FALSE));
  g_error ("hi?");

  if (error)
    g_error ("connect: %s: %d, %s", g_quark_to_string (error->domain), error->code, error->message);

  input = g_io_stream_get_input_stream (G_IO_STREAM (connection));

  while (TRUE)
    {
      bytes = g_input_stream_read (input, buffer,
                                   sizeof buffer,
                                   NULL, NULL);

      g_print ("%"G_GSSIZE_FORMAT" bytes read\n", bytes);
    }
}

