"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.fetchLayoutResolver = fetchLayoutResolver;
const arcgis_rest_portal_1 = require("@esri/arcgis-rest-portal");
const findNodeById_1 = require("../findNodeById");
/**
 * Resolves a layout:// reference by fetching the layout (or node) from item data.
 * Example `$ref: "layout://item/:itemId/:nodeId"`
 * @param ref The layout reference to resolve.
 * @param context The ArcGIS context for making the request.
 * @returns The resolved layout or node, or undefined if not found.
 * @throws Error if the ref is invalid or the item cannot be fetched.
 */
async function fetchLayoutResolver(ref, context) {
    let normalizedRef = ref;
    if (normalizedRef.endsWith("#")) {
        normalizedRef = normalizedRef.slice(0, -1);
    }
    const parts = normalizedRef.split("/");
    const id = parts[3];
    const nodeId = parts[4] || "";
    if (!id) {
        throw new Error(`fetchLayoutResolver: invalid ref "${ref}"`);
    }
    let data;
    try {
        data = (await (0, arcgis_rest_portal_1.getItemData)(id, context.requestOptions));
    }
    catch (_error) {
        throw new Error(`fetchLayoutResolver: could not fetch layout ${ref}`);
    }
    const fetchedLayout = data.layout;
    let node = fetchedLayout;
    if (nodeId) {
        node = (0, findNodeById_1.findNodeById)(fetchedLayout, nodeId);
    }
    if (node) {
        node.readOnly = true;
    }
    return node;
}
//# sourceMappingURL=fetchLayoutResolver.js.map