/*
 * Win32 implementation of the GDir subset used by q3map2's vfs.cpp.
 * Uses FindFirstFileA / FindNextFileA / FindClose.
 */

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

extern "C" {

typedef struct _GDir {
    HANDLE          handle;
    WIN32_FIND_DATAA findData;
    char            name[MAX_PATH];
    int             first;  /* 1 = first entry not yet consumed */
} GDir;

GDir* g_dir_open(const char* path, unsigned int flags, void* error)
{
    (void)flags; (void)error;

    char pattern[MAX_PATH];
    _snprintf(pattern, sizeof(pattern), "%s\\*", path);
    pattern[sizeof(pattern) - 1] = '\0';

    WIN32_FIND_DATAA fd;
    HANDLE h = FindFirstFileA(pattern, &fd);
    if (h == INVALID_HANDLE_VALUE)
        return NULL;

    GDir* dir = (GDir*)malloc(sizeof(GDir));
    if (!dir) { FindClose(h); return NULL; }

    dir->handle = h;
    dir->findData = fd;
    dir->first = 1;
    return dir;
}

const char* g_dir_read_name(GDir* dir)
{
    if (!dir)
        return NULL;

    for (;;) {
        const char* name;
        if (dir->first) {
            dir->first = 0;
            name = dir->findData.cFileName;
        } else {
            if (!FindNextFileA(dir->handle, &dir->findData))
                return NULL;
            name = dir->findData.cFileName;
        }

        /* skip . and .. */
        if (name[0] == '.' && (name[1] == '\0' || (name[1] == '.' && name[2] == '\0')))
            continue;

        strncpy(dir->name, name, MAX_PATH - 1);
        dir->name[MAX_PATH - 1] = '\0';
        return dir->name;
    }
}

void g_dir_close(GDir* dir)
{
    if (dir) {
        FindClose(dir->handle);
        free(dir);
    }
}

} /* extern "C" */
