"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_extra_1 = __importDefault(require("fs-extra"));
const fast_xml_parser_1 = __importDefault(require("fast-xml-parser"));
const debug_1 = __importDefault(require("debug"));
const debug = debug_1.default('localdevserver');
function resolver(options = {}) {
    const { customLabelsPath } = options;
    if (customLabelsPath && !fs_extra_1.default.existsSync(customLabelsPath)) {
        throw new Error(`labels file '${customLabelsPath}' does not exist`);
    }
    return {
        createProxiedObject() {
            const customLabelsProxy = new Proxy({}, {
                get(obj, prop) {
                    debug(`get: ${String(prop)}`);
                    if (typeof prop === 'string') {
                        const labels = loadCustomLabels(customLabelsPath);
                        if (prop in labels) {
                            return labels[prop];
                        }
                        return `{unknown label: c.${prop}}`;
                    }
                }
            });
            return {
                c: customLabelsProxy
            };
        }
    };
}
exports.default = resolver;
function loadCustomLabels(labelsPath) {
    debug('loading custom labels');
    if (!labelsPath || !fs_extra_1.default.existsSync(labelsPath)) {
        debug('custom labels file not specified or does not exist');
        return {};
    }
    const xmlContent = fs_extra_1.default.readFileSync(labelsPath, 'utf8');
    const parsedXml = fast_xml_parser_1.default.parse(xmlContent);
    if (!parsedXml.CustomLabels || !parsedXml.CustomLabels.labels) {
        console.warn(`custom labels file '${labelsPath}' did not have expected format or was empty, ignoring.`);
        return {};
    }
    let labels = parsedXml.CustomLabels.labels;
    if (!Array.isArray(labels)) {
        labels = [labels];
    }
    const processed = labels.reduce((obj, label) => {
        if (label.fullName && label.value) {
            obj[label.fullName] = label.value;
        }
        return obj;
    }, {});
    debug(`found custom labels: ${JSON.stringify(processed, null, 2)}`);
    return processed;
}
//# sourceMappingURL=labelResolver.js.map