"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const node_path_1 = require("node:path");
const Local_1 = require("./Local");
const ReferenceCountMap_1 = __importDefault(require("./utils/ReferenceCountMap"));
class default_1 {
    constructor(listener, onMissing, transform = (files) => files) {
        this.listener = listener;
        this.onMissing = onMissing;
        this.transform = transform;
        this.watched = new ReferenceCountMap_1.default;
    }
    watch(dir) {
        try {
            this.watched.inc(dir) || this.watched.set(dir, (0, Local_1.watch)(dir, (event, target) => {
                if (event == 'rename') {
                    const child = (0, node_path_1.join)(dir, target);
                    if (this.watched.has(child) && !(0, Local_1.stat)(child)) {
                        this.watched.del(child);
                        this.onMissing(child);
                    }
                }
                try {
                    this.listener(dir, this.transform((0, Local_1.list)(dir)), event, target);
                }
                catch (e) {
                    this.watched.del(dir);
                    this.onMissing(dir);
                }
            }));
            const files = this.transform((0, Local_1.list)(dir));
            this.listener(dir, files);
            return files;
        }
        catch (e) {
            this.watched.del(dir);
            this.onMissing(dir);
        }
        return [];
    }
    unwatch(dir) {
        this.watched.dec(dir)?.();
    }
}
exports.default = default_1;
