"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RootConfigWatcher = void 0;
const chokidar_1 = __importDefault(require("chokidar"));
const promises_1 = require("node:fs/promises");
const configUtils_js_1 = require("./configUtils.js");
const node_events_1 = require("node:events");
const yaml_1 = require("yaml");
class RootConfigWatcher extends node_events_1.EventEmitter {
    #configFilePath;
    #watcher;
    #config;
    ready;
    constructor() {
        super();
        this.#configFilePath = (0, configUtils_js_1.getConfigFilePath)();
        this.ready = (0, node_events_1.once)(this, 'ready');
        this.#watcher = chokidar_1.default
            .watch(this.#configFilePath, { persistent: false })
            .on('add', this.handleChange.bind(this))
            .on('change', this.handleChange.bind(this))
            .on('error', this.handleError.bind(this));
    }
    handleError(error) {
        this.emit('error', error);
    }
    handleChange() {
        (0, promises_1.readFile)(this.#configFilePath, 'utf-8')
            .then((data) => {
            if (!data)
                return;
            const config = (0, yaml_1.parse)(data);
            if (!this.#config) {
                this.#config = config;
                this.emit('ready', this.#config);
                return;
            }
            this.emit('change', (this.#config = config));
        })
            .catch((_error) => {
            // if yaml parse error ignore?
        });
    }
    close() {
        this.#watcher.close();
        this.#config = undefined;
        this.emit('close');
        this.removeAllListeners();
        return this;
    }
    get config() {
        return this.#config;
    }
}
exports.RootConfigWatcher = RootConfigWatcher;
//# sourceMappingURL=RootConfigWatcher.js.map