#include "read_input.h"

uint8_t read_input(keypress **input, size_t *input_len, bool *lock, bool is_broken, uint64_t delay) {

  size_t arr_len = ARR_LEN;

  if (!(*input = malloc(sizeof(keypress) * arr_len)))
    return 0;

  struct pollfd polling[1];

  polling[0].fd = STDIN_FILENO;
  polling[0].events = POLLIN;

  if(is_broken) {
    (*input)[0] = ESCAPE_KEY;
    (*input_len)++;

    break_unfinished();
  }

  int is_poll = poll(polling, 1, delay);

  if (is_poll > 0 && polling[0].revents & POLLIN) {

    char string[256] = {};
    ssize_t length_string = read(STDIN_FILENO, string, sizeof(string) - 1);
 
    if (add_to_buf(string, length_string)) {

      do {

        if (*input_len >= arr_len) {
          arr_len *= 2;
          keypress *tmp = realloc(*input, sizeof(keypress) * arr_len);
          if (tmp == NULL) {
            free(*input);
            return 0;
          }
          *input = tmp;
        }

        (*input)[*input_len] = parse_input();

        if ((*input)[*input_len] == INCOMPLETE) {
          *lock = true;
          break;
        } 

      } while ((*input)[(*input_len)++] != NO_KEY);
    }
  }

  return 1;
}

void free_input(keypress *input) {
  free(input);
}


