/* COPYRIGHT Esri - https://js.arcgis.com/5.0.18/LICENSE.txt */
import e from"../../core/Error.js";import{allSettledErrors as t,throwIfAborted as r,eachAlways as o}from"../../core/promiseUtils.js";import{generateUUID as s}from"../../core/uuid.js";import{getSiblingOfSameTypeI as a,contentToBlob as c}from"../../portal/support/resourceUtils.js";async function p(e,t,r){const o=await u(e,t,r);await h(o,t,r)}async function n(e,t,r,o,s){const a=await u(r,o,s);await e.update({data:t}),await h(a,o,s)}async function u(o,p,n){if(!p?.resources)return;const u=p.portalItem===o.portalItem?new Set(o.paths):new Set;o.paths.length=0,o.portalItem=p.portalItem;const h=new Set(p.resources.toKeep.map(e=>e.resource.path)),i=new Set,m=[];h.forEach(e=>{u.delete(e),o.paths.push(e)});const f=[],l=[],w=[];for(const e of p.resources.toUpdate)if(u.delete(e.resource.path),h.has(e.resource.path)||i.has(e.resource.path)){const{resource:t,content:r,finish:p}=e,n=a(t,s());o.paths.push(n.path),f.push({resource:n,content:await c(r),compress:e.compress}),p&&w.push(()=>p(n))}else{o.paths.push(e.resource.path),l.push({resource:e.resource,content:await c(e.content),compress:e.compress});const t=e.finish;t&&w.push(()=>t(e.resource)),i.add(e.resource.path)}for(const e of p.resources.toAdd)if(o.paths.push(e.resource.path),u.has(e.resource.path))u.delete(e.resource.path);else{f.push({resource:e.resource,content:await c(e.content),compress:e.compress});const t=e.finish;t&&w.push(()=>t(e.resource))}if(f.length||l.length){const{addOrUpdateResources:e}=await import("../../portal/support/resourceUtils.js");await e(p.portalItem,f,"add",n),await e(p.portalItem,l,"update",n)}if(w.forEach(e=>e()),0===m.length)return u;const d=await t(m);if(r(n),d.length>0)throw new e("save:resources","Failed to save one or more resources",{errors:d});return u}async function h(e,t,r){if(!e||!t.portalItem)return;const s=[];for(const o of e){const e=t.portalItem.resourceFromPath(o);s.push(e.portalItem.removeResource(e,r))}await o(s)}export{p as saveResources,n as updateItemWithResources};
