"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.YamlLinks = void 0;
const vscode_languageserver_types_1 = require("vscode-languageserver-types");
const yaml_documents_1 = require("../parser/yaml-documents");
class YamlLinks {
    constructor(telemetry) {
        this.telemetry = telemetry;
    }
    async findLinks(document) {
        try {
            const doc = yaml_documents_1.yamlDocumentsCache.getYamlDocument(document);
            // Find links across all YAML Documents then report them back once finished
            const linkPromises = [];
            for (const yamlDoc of doc.documents) {
                linkPromises.push(findDocumentLinks(document, yamlDoc));
            }
            // Wait for all the promises to return and then flatten them into one DocumentLink array
            const yamlLinkArray = await Promise.all(linkPromises);
            return [].concat(...yamlLinkArray);
        }
        catch (err) {
            this.telemetry?.sendError('yaml.documentLink.error', err);
        }
    }
}
exports.YamlLinks = YamlLinks;
// Copied from vscode-json-languageservice@6.0.0-next.1
// Source: https://github.com/microsoft/vscode-json-languageservice/blob/810471bbb462bb6b87351c2232e209a3bb4062ca/src/services/jsonLinks.ts
function findDocumentLinks(document, doc) {
    const links = [];
    doc.visit((node) => {
        if (node.type === 'property' && node.keyNode.value === '$ref' && node.valueNode?.type === 'string') {
            const path = node.valueNode.value;
            const targetNode = findTargetNode(doc, path);
            if (targetNode) {
                const targetPos = document.positionAt(targetNode.offset);
                links.push({
                    target: `${document.uri}#${targetPos.line + 1},${targetPos.character + 1}`,
                    range: createRange(document, node.valueNode),
                });
            }
        }
        return true;
    });
    return Promise.resolve(links);
}
function createRange(document, node) {
    return vscode_languageserver_types_1.Range.create(document.positionAt(node.offset + 1), document.positionAt(node.offset + node.length - 1));
}
function findTargetNode(doc, path) {
    const tokens = parseJSONPointer(path);
    if (!tokens) {
        return null;
    }
    return findNode(tokens, doc.root);
}
function findNode(pointer, node) {
    if (!node) {
        return null;
    }
    if (pointer.length === 0) {
        return node;
    }
    const token = pointer.shift();
    if (node && node.type === 'object') {
        const propertyNode = node.properties.find((propertyNode) => propertyNode.keyNode.value === token);
        if (!propertyNode) {
            return null;
        }
        return findNode(pointer, propertyNode.valueNode);
    }
    else if (node && node.type === 'array') {
        if (token.match(/^(0|[1-9][0-9]*)$/)) {
            const index = Number.parseInt(token);
            const arrayItem = node.items[index];
            if (!arrayItem) {
                return null;
            }
            return findNode(pointer, arrayItem);
        }
    }
    return null;
}
function parseJSONPointer(path) {
    if (path === '#') {
        return [];
    }
    if (path[0] !== '#' || path[1] !== '/') {
        return null;
    }
    return path.substring(2).split(/\//).map(unescape);
}
function unescape(str) {
    return str.replace(/~1/g, '/').replace(/~0/g, '~');
}
//# sourceMappingURL=yamlLinks.js.map