#ifndef STRING_OP_C
#define STRING_OP_C

#include "vector.c"
#include <stdlib.h>
#include <string.h>

vector_t *split_string(char *str, char delimiter) {
  vector_t *result = vector_create(1);
  size_t start = 0;
  size_t len = strlen(str);

  for (size_t i = 0; i <= len; i++) {
    if (str[i] == delimiter || str[i] == '\0') {
      size_t part_len = i - start;
      char *part = malloc((part_len + 1) * sizeof(char));
      if (part == NULL) {
        vector_destroy(result);
        return NULL;
      }
      strncpy(part, &str[start], part_len);
      part[part_len] = '\0';
      if (vector_push(result, part) != 0) {
        free(part);
        vector_destroy(result);
        return NULL;
      }
      start = i + 1;
    }
  }

  return result;
}

int test_split_string() {
  printf("--- START TEST:\t split_string ---\n");
  char *test_str = "hello,world,this,is,a,test";
  vector_t *parts = split_string(test_str, ',');
  if (parts == NULL) {
    printf("split_string returned NULL\n");
    return 1;
  }

  printf("Split parts:\n");
  for (size_t i = 0; i < parts->length; i++) {
    char *part = (char *)vector_get(parts, i);
    printf("Part %zu: %s\n", i, part);
    free(part);
  }
  vector_destroy(parts);

  printf("--- END TEST:\t split_string ---\n");

  return 0;
}

#endif
