#include "../include/util/util.h"
#include "../include/lib/hb_allocator.h"
#include "../include/lib/hb_buffer.h"
#include "../include/lib/hb_string.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int is_newline(int character) {
  return character == '\n' || character == '\r';
}

int is_whitespace(int character) {
  return character == ' ' || character == '\t' || character == '\n' || character == '\r';
}

hb_string_T escape_newlines(hb_allocator_T* allocator, hb_string_T input) {
  hb_buffer_T buffer;

  hb_buffer_init(&buffer, input.length, allocator);

  for (size_t i = 0; i < input.length; ++i) {
    switch (input.data[i]) {
      case '\n': {
        hb_buffer_append_char(&buffer, '\\');
        hb_buffer_append_char(&buffer, 'n');
      } break;
      case '\r': {
        hb_buffer_append_char(&buffer, '\\');
        hb_buffer_append_char(&buffer, 'r');
      } break;
      default: {
        hb_buffer_append_char(&buffer, input.data[i]);
      }
    }
  }

  return hb_string(buffer.value);
}

static hb_string_T wrap_string(hb_allocator_T* allocator, hb_string_T input, char character) {
  hb_buffer_T buffer;

  hb_buffer_init(&buffer, input.length + 2, allocator);

  hb_buffer_append_char(&buffer, character);
  hb_buffer_append_string(&buffer, input);
  hb_buffer_append_char(&buffer, character);

  return hb_string(buffer.value);
}

hb_string_T quoted_string(hb_allocator_T* allocator, hb_string_T input) {
  return wrap_string(allocator, input, '"');
}

char* convert_underscores_to_dashes(const char* input) {
  if (!input) { return NULL; }

  size_t len = strlen(input);
  char* output = calloc(len + 1, sizeof(char));
  if (!output) { return NULL; }

  for (size_t i = 0; i < len; i++) {
    output[i] = (input[i] == '_') ? '-' : input[i];
  }

  return output;
}
