// SPDX-License-Identifier: LGPL-3.0-or-later

/* Portable low level system directory access.
 *
 * Copyright: 2022, The DoubleFourteen Code Forge
 * Author: Lorenzo Cogotti
 */

#ifndef DF_LUA_OSXDIR_H_
#define DF_LUA_OSXDIR_H_

#include "lua.h"

#ifdef _WIN32
#include <io.h>

typedef struct {
    intptr_t dirh;    // raw system directory handle
    _Bool startflag;  // whether data references the first directory entry
    _Bool endflag;    // whether we've made to the end of the directory
    _Bool errflag;    // whether last call encountered an error
    struct _finddata_t data;  // directory entry info
} *df_os_dirhn;

#ifdef DF_LUA_OSXLIB
#define DF_OSXLIB_API __declspec(dllexport)
#else
#define DF_OSXLIB_API __declspec(dllimport)
#endif

#else
#include <dirent.h>

typedef DIR *df_os_dirhn;

#define DF_OSXLIB_API
#endif

/* Open directory at 'path' (not NULL).
 * Returns opened directory handle on success, NULL on failure (sets errno).
 */
DF_OSXLIB_API df_os_dirhn os_opendir(const char *path);

/* Read next entry from opened directory handle 'hn' (not NULL).
 * Returns:
 * - next entry filename on success.
 * - NULL leaving errno unchanged when no more entries are available.
 * - NULL and sets errno on failure.
 */
DF_OSXLIB_API char *os_readdir(df_os_dirhn hn);

/* Close opened directory handle 'hn' (not NULL). */
DF_OSXLIB_API void os_closedir(df_os_dirhn hn);

#endif