/**
 * dirtools.c:
 *
 * Useful tools for manipulating directory names,
 * or pretty much anything involving directories.
**/
#include "dirtools.h"

#include <windef.h>
#include <fileapi.h>
#include <errhandlingapi.h>
#include <winerror.h>

static int dirtools_directory_exists(LPCWSTR restrict path) {
	DWORD attrib = GetFileAttributesW(path);
	return (attrib != INVALID_FILE_ATTRIBUTES && (attrib & FILE_ATTRIBUTE_DIRECTORY));
}

int dirtools_create_directory(LPCWSTR restrict path) {
	size_t len = wcslen(path);
	WCHAR tmp[len + 1];
	memset(tmp, '\0', (len + 1) * sizeof(WCHAR));

	for (size_t i = 0; i < len; i++) {
		if (path[i] != L'\\')
			continue;

		wcsncpy(tmp, path, i);
		if (dirtools_directory_exists(tmp))
			continue;

		if (!CreateDirectoryW(tmp, NULL))
			if (GetLastError() == ERROR_PATH_NOT_FOUND)
				return 1;
	}

	if (!dirtools_directory_exists(path) && !CreateDirectoryW(path, NULL))
		if (GetLastError() == ERROR_PATH_NOT_FOUND)
			return 1;

	return 0;
}

LPWSTR dirtools_concat_paths(LPCWSTR restrict a, LPCWSTR restrict b) {
	if (a[0] == L'\0' || b[0] == L'\0')
		return NULL;

	const size_t a_len = wcslen(a);
	const size_t b_len = wcslen(b);
	const int add_backslash = (a[a_len] != L'\\' && b[0] != L'\\');

	LPWSTR out = calloc(a_len + b_len + 1 + add_backslash, sizeof(WCHAR));
	if (out == NULL)
		return out;

	wcscpy(out, a);
	if (add_backslash)
		wcscat(out, L"\\");

	wcscat(out, b);
	return out;
}
