#include <path.h>
#include <stdbool.h>
#include <stddef.h>

bool path_validate_char (char ch) {
  return ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
          (ch == '_') || (ch == '-') || (ch == '/') || (ch == '.'));
}

bool path_validate (const char* path) {
  if (path == NULL || *path == '\0')
    return false;

  const char* ptr = path;

  if (*ptr != '/')
    return false;

  while (*ptr != '\0') {
    if (*ptr == '/' && *(ptr + 1) == '/')
      return false;

    if (!path_validate_char (*ptr))
      return false;

    ptr++;
  }

  if (ptr > path + 1 && *(ptr - 1) == '/')
    return false;

  return true;
}

bool path_parse (const char* source, char* volume, const char** path) {
  if (source == NULL || volume == NULL || path == NULL)
    return false;

  size_t i = 0;

  while (source[i] != ':' && source[i] != '\0') {
    if (i >= (VOLUME_MAX - 1))
      return false;

    volume[i] = source[i];
    i++;
  }

  if (source[i] != ':' || i == 0)
    return false;

  volume[i] = '\0';

  const char* internal_path = &source[i + 1];

  if (!path_validate (internal_path))
    return false;

  *path = internal_path;
  return true;
}

const char* path_basename (const char* path) {
  if (path == NULL)
    return NULL;

  const char* last_slash = NULL;
  const char* ptr = path;

  while (*ptr != '\0') {
    if (*ptr == '/')
      last_slash = ptr;

    ptr++;
  }

  if (last_slash == NULL)
    return path;

  return last_slash + 1;
}
