#include "config.h"

#ifdef USE_GETLINE
#define _WITH_GETLINE /* for FreeBSD */
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef USE_LIBEDIT
#include <editline/readline.h>
#endif
#ifdef USE_EDITLINE
#include <editline.h>
#endif
#ifdef USE_READLINE
#include <readline/readline.h>
#include <readline/history.h>
#endif
#ifdef USE_NLLINE
#include <nlline.h>
#endif

#ifdef USE_NLLIBC
#include <nllibc.h>
#endif

#include "nlltypes.h"
#include "line.h"
#include "readline.h"

#ifdef USE_GETLINE
static char *getline_readline(const char *prompt)
{
  char *buffer;
  int size;
  size_t buffer_size = 0;

  fputs(prompt, stdout);
  buffer = NULL;
  size = getline(&buffer, &buffer_size, stdin);
  if (size < 0)
    return NULL;

  return buffer;
}

static void getline_add_history(const char *line)
{
  return;
}

#define readline(prompt) getline_readline(prompt)
#define add_history(line) getline_add_history(line)
#endif

#ifdef USE_FGETS
static char *fgets_readline(const char *prompt)
{
  char *buffer;
  int len;
#define LINE_BUFFER_SIZE 1024

  fputs(prompt, stdout);
  buffer = malloc(LINE_BUFFER_SIZE);
  if (buffer) {
    if (fgets(buffer, LINE_BUFFER_SIZE, stdin) == NULL) {
      free(buffer);
      return NULL;
    }

    len = strlen(buffer);
    if ((len > 0) && (buffer[len - 1] == '\n'))
      buffer[len - 1] = '\0';
  }

  return buffer;
}

static void fgets_add_history(const char *line)
{
  return;
}

#define readline(prompt) fgets_readline(prompt)
#define add_history(line) fgets_add_history(line)
#endif

char *nll_readline(const char *prompt)
{
  return readline(prompt);
}

void nll_add_history(const char *line)
{
  add_history(line);
}

void nll_edit_line(int number, line_t line)
{
  char buffer[32 + LINE_MAXLEN + 1];
  if (line) {
    sprintf(buffer, "%d %d%s", number, number, line->buffer);
    add_history(buffer);
  }
}
