// SPDX-License-Identifier: Apache-2.0
import { Lexer } from './lexer.js';
import { ConfigKeyFormatter } from '../config-key-formatter.js';
import { IllegalArgumentError } from '../../../business/errors/illegal-argument-error.js';
export class Forest {
    lexer;
    formatter;
    constructor(lexer, formatter) {
        this.lexer = lexer;
        this.formatter = formatter;
        if (!lexer) {
            throw new IllegalArgumentError('lexer must not be null or undefined');
        }
        if (!formatter) {
            throw new IllegalArgumentError('formatter must not be null or undefined');
        }
    }
    static from(data, formatter = ConfigKeyFormatter.instance()) {
        const lexer = new Lexer(data, formatter);
        lexer.renderTrees();
        return new Forest(lexer, formatter);
    }
    static fromLexer(lexer, formatter = ConfigKeyFormatter.instance()) {
        if (!lexer) {
            throw new IllegalArgumentError('lexer must not be null or undefined');
        }
        return new Forest(lexer, formatter);
    }
    has(key) {
        if (!key) {
            throw new IllegalArgumentError('key must not be null or undefined');
        }
        return this.nodeFor(key) !== null;
    }
    valueFor(key) {
        if (!key) {
            throw new IllegalArgumentError('key must not be null or undefined');
        }
        const node = this.nodeFor(key);
        if (!node) {
            return null;
        }
        if (node.isLeaf()) {
            return node.value;
        }
        return null;
    }
    nodeFor(key) {
        return this.lexer.nodeFor(key);
    }
    addOrReplaceValue(key, value) {
        this.lexer.addOrReplaceValue(key, value);
    }
    addOrReplaceObject(key, value) {
        this.lexer.addOrReplaceObject(key, value);
    }
    addOrReplaceArray(key, values) {
        this.lexer.addOrReplaceArray(key, values);
    }
    toObject() {
        const object = {};
        for (const [key, node] of this.lexer.tree.entries()) {
            object[key] = node.isLeaf() ? node.value : node.toObject();
        }
        return object;
    }
    toFlatMap() {
        return this.lexer.tokens;
    }
}
//# sourceMappingURL=forest.js.map