import { cloneObject } from "../util.js";
import { upsertLayoutResource } from "./upsertLayoutResource.js";
export async function updateLayout(entity, layout, requestOptions) {
    if (!layout) {
        return layout;
    }
    const updatedLayout = cloneObject(layout);
    // check the variables and for each one that is of type image and... has a source, a blob?
    // we need to upload the image as a resource and update the variable.value to point to the resource and remove all other properties except type
    await Promise.all(Object.entries(updatedLayout.variables || {}).map(async ([key, _variable]) => {
        const variable = _variable;
        if (variable.type === "image") {
            if (variable.source === "upload" && !!variable.blob) {
                const newVariable = {
                    type: variable.type,
                };
                const resourceUrl = await upsertLayoutResource(entity.id, entity.owner, variable.blob, key, // this is something like <nodeId>-image-card
                variable.format, requestOptions);
                // set the value to the resource name
                newVariable.value = { $ref: resourceUrl };
                updatedLayout.variables[key] = newVariable;
            }
        }
    }));
    /*
      TODO: we will also need to clean up any old resources that are no longer referenced
            - make sure when we delete it in the ui, we get rid of the variable
            - then when we save, we delete any resources for which there is no variable
            - when an image card is changed from an upload to a url, we will handle it similarly
    */
    return updatedLayout;
}
//# sourceMappingURL=updateLayout.js.map