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

#include "../logger.h"
#include "types.h"
#include "utils.h"

generic_array_t create_array(size_t elem_size, size_t n) {
  generic_array_t array;
  array.data = n ? malloc(elem_size * n) : NULL;
  array.elem_size = elem_size;
  array.n = n;
  return array;
}

void free_array(generic_array_t *array) {
  FREE_AND_NULLIFY(array->data);
  array->n = 0;
}

void resize_array(generic_array_t *array, size_t new_size) {
  if (new_size) {
    array->data = realloc(array->data, array->elem_size * new_size);
  } else {
    size_t elem_size = array->elem_size;
    free_array(array);
    create_array(elem_size, 0);
  }
  array->n = new_size;
}

void *get_element(generic_array_t *array, size_t index) {
  if (index >= array->n) {
    return NULL; // Out of bounds
  }
  return (char *)array->data + index * array->elem_size;
}

/* A more specific impl, specially for string (char *) */

str_array_t create_str_array(size_t n) {
  str_array_t array;
  array.str = n ? malloc(n * sizeof(char *)) : NULL;
  array.n = n;
  for (size_t i = 0; i < n; i++) {
    array.str[i] = NULL;
  }
  return array;
}

// NOTE: would free both the array and all its elements
void free_str_array(str_array_t *array) {
  for (size_t i = 0; i < array->n; i++) {
    free(array->str[i]);
  }
  FREE_AND_NULLIFY(array->str);
  array->n = 0;
}

void resize_str_array(str_array_t *array, size_t new_size) {
  if (new_size) {
    array->str = realloc(array->str, sizeof(char *) * new_size);
    for (size_t i = array->n; i < new_size; i++) {
      array->str[i] = NULL;
    }
  } else {
    free_str_array(array);
    *array = create_str_array(0);
  }
  array->n = new_size;
}

int set_str_element(str_array_t *array, size_t index, const char *value) {
  if (index >= array->n) {
    return 1; // Out of bounds
  }
  array->str[index] = malloc(strlen(value) + 1);
  strcpy(array->str[index], value);
  return 0;
}

const char *get_str_element(str_array_t *array, size_t index) {
  if (index >= array->n) {
    return NULL; // Out of bounds
  }
  return array->str[index];
}

queue_t create_queue(void) {
  queue_t queue;
  queue.front = queue.rear = NULL;
  return queue;
}

int is_empty_queue(queue_t *queue) { return queue->front == NULL; }

void enqueue(queue_t *queue, data_t data) {
  node_t *node = malloc(sizeof(node_t));
  node->data = data;
  node->next = NULL;
  if (queue->rear == NULL) {
    queue->rear = queue->front = node;
  } else {
    queue->rear->next = node;
    queue->rear = node;
  }
}

data_t dequeue(queue_t *queue) {
  if (is_empty_queue(queue)) {
    DEBUG_PRINT("Queue is empty.\n");
    return NULL;
  }

  node_t *temp = queue->front;
  data_t data = temp->data;
  queue->front = temp->next;
  FREE_AND_NULLIFY(temp);

  if (queue->front == NULL) {
    queue->rear = NULL;
  }

  return data;
}

void free_queue(queue_t *queue) {
  while (!is_empty_queue(queue)) {
    dequeue(queue);
  }
}