#include <sys/types.h>
#include <sys/stat.h>
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

#include <microhttpd.h>

typedef struct state_s {
  int paused;
  int count;
} state_t;

static ssize_t content_reader(
    void * data,
    uint64_t pos,
    char * buf,
    size_t max
) {
  state_t * state = (state_t *)data;

  /* We send 20 greetings with a pause at the 10th one. */
  if (state->count >= 20)
    return MHD_CONTENT_READER_END_OF_STREAM;

  if (state->count == 10 && !state->paused) {
    sleep(2);
    state->paused = 1;
    return 0;
  }

  state->count++;
  strcpy(buf, "Hello World!\n");
  return strlen("Hello World!\n");
}

static int access_handler(
    void * data,
    struct MHD_Connection * connection,
    const char * url,
    const char * method,
    const char * version,
    const char * upload_data,
    size_t * upload_data_size,
    void ** connection_data
) {
  struct MHD_Response * response;
  int result;
  state_t * state;

  state = malloc(sizeof(state_t));
  assert(state != NULL);
  state->paused = 0;
  state->count = 0;

  response = MHD_create_response_from_callback(MHD_SIZE_UNKNOWN, 2048,
      content_reader, state, free);
  assert(response != NULL);

  result = MHD_queue_response(connection, 200, response);
  assert(result == MHD_YES);

  *connection_data = response;

  return MHD_YES;
}

int main(
    int argc,
    char ** argv
) {
  struct MHD_Daemon * daemon;

  daemon = MHD_start_daemon(MHD_USE_INTERNAL_POLLING_THREAD |
      MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG,
      8081,
      NULL, NULL,
      access_handler, NULL,
      MHD_OPTION_END);
  assert(daemon != NULL);

  while (1)
    sleep(1000);

  return 0;
}
