"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 ReferenceCountMap_1 = __importDefault(require("./utils/ReferenceCountMap"));
const Connection_1 = __importDefault(require("./Connection"));
const URI_1 = require("./utils/URI");
class RemoteWatcher {
    constructor(listener, onMissing, transform = (files) => files) {
        this.listener = listener;
        this.onMissing = onMissing;
        this.transform = transform;
        this.watched = new ReferenceCountMap_1.default;
    }
    watch(uri) {
        this.watched.inc(uri) || this.watched.set(uri, false);
        this.refresh(uri);
    }
    unwatch(uri) {
        this.watched.dec(uri);
    }
    refresh(uri) {
        if (this.watched.has(uri)) {
            this.list(uri);
            Array.from(this.watched.keys()).forEach(dir => {
                if (dir.startsWith(uri + node_path_1.sep)) {
                    this.list(dir);
                }
            });
        }
    }
    list(uri) {
        const { id, path } = (0, URI_1.parseURI)(uri);
        Connection_1.default.list(id, path)
            .then(files => this.listener(uri, this.transform(files)))
            .catch(e => {
            this.watched.del(uri);
            this.onMissing(uri);
        });
    }
}
exports.default = RemoteWatcher;
