"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CustomDir = void 0;
exports.opendir = opendir;
const tslib_1 = require("tslib");
const errors = tslib_1.__importStar(require("../errors"));
class CustomDir {
    constructor(path, nextDirent, opts = {}) {
        this.path = path;
        this.nextDirent = nextDirent;
        this.opts = opts;
        this.closed = false;
    }
    throwIfClosed() {
        if (this.closed) {
            throw errors.ERR_DIR_CLOSED();
        }
    }
    async *[Symbol.asyncIterator]() {
        try {
            let dirent;
            while ((dirent = await this.read()) !== null) {
                yield dirent;
            }
        }
        finally {
            await this.close();
        }
    }
    read(cb) {
        const dirent = this.readSync();
        if (typeof cb !== `undefined`)
            return cb(null, dirent);
        return Promise.resolve(dirent);
    }
    readSync() {
        this.throwIfClosed();
        return this.nextDirent();
    }
    close(cb) {
        this.closeSync();
        if (typeof cb !== `undefined`)
            return cb(null);
        return Promise.resolve();
    }
    closeSync() {
        this.throwIfClosed();
        this.opts.onClose?.();
        this.closed = true;
    }
}
exports.CustomDir = CustomDir;
function opendir(fakeFs, path, entries, opts) {
    const nextDirent = () => {
        const filename = entries.shift();
        if (typeof filename === `undefined`)
            return null;
        const entryPath = fakeFs.pathUtils.join(path, filename);
        return Object.assign(fakeFs.statSync(entryPath), {
            name: filename,
            path: undefined,
        });
    };
    return new CustomDir(path, nextDirent, opts);
}
