import{createFeatureServices as e}from"@arcgis/core/rest/featureService/utils";import{FeatureSaveError as t}from"../../data/FeatureSaveError.js";import{applyEditsProcessEditedFeatures as a,applyEditsProcessResults as s}from"../../support/_featureEdit.js";import{getGdbVersion as r}from"../../utilities/_version.js";import{isFeatureLayerExtension as d,isSubtypeGroupLayerExtension as u,isSubtypeSublayerExtension as i}from"../../utilities/extensions.js";import{map as o}from"../../utilities/iterable.js";import{getGlobalIdField as l,isGlobalIdUsed as n}from"./layers.js";export async function applyEdits(c){const{addFeatures:p=[],updateFeatures:m=[],deleteFeatures:F=[]}=c,f=new Map,h=new WeakMap,g=new WeakMap,y=new WeakMap,E=(e,t)=>{const a=(e=>d(e.source)||u(e.source)?e.source.layer:i(e.source)?e.source.layerExtension.layer:e.source.table)(e),s=l(a),{objectIdField:r}=a;f.has(a)||f.set(a,{id:a.layerId,identifierFields:{globalIdField:s,objectIdField:r},addFeatures:[],updateFeatures:[],deleteFeatures:[],addAttachments:void 0,updateAttachments:void 0,deleteAttachments:void 0});const o=f.get(a),n=e.toGraphic();"updateFeatures"===t&&e.source?.schema.fieldExtensions.forEach((e=>{e.field.editable||e.field.name===r||e.field.name===s||delete n.attributes[e.field.name]})),o[t].push(n);let c=h;"updateFeatures"===t?c=g:"deleteFeatures"===t&&(c=y),c.has(a)||c.set(a,[]),c.get(a).push(e)};p.forEach((e=>E(e,"addFeatures"))),m.forEach((e=>E(e,"updateFeatures"))),F.forEach((e=>E(e,"deleteFeatures")));const b=e([...f.keys()]),w=new t("Errors encountered when applying edits."),v=await Promise.all(o(b.values(),(async({featureService:e,layers:t})=>{await e.load();const d=[];t.forEach((e=>{d.push(f.get(e))}));try{const u=await e.applyEdits(d,{globalIdUsed:t.every((e=>n(e,f.get(e)))),gdbVersion:t[0].gdbVersion??r(t[0].customParameters)});for(const e of u){const r=t.find((t=>t.layerId===e.id));null!=r&&(s(r,h.get(r),e.addFeatureResults,"add",w),s(r,g.get(r),e.updateFeatureResults,"update",w),s(r,y.get(r),e.deleteFeatureResults,"delete",w),null!=e.editedFeatures&&a(r,{adds:h.get(r),updates:g.get(r)},e.editedFeatures),r.emit("edits",{deletedFeatures:e.deleteFeatureResults??[],updatedFeatures:e.updateFeatureResults??[],addedFeatures:e.addFeatureResults??[],deletedAttachments:[],updatedAttachments:[],addedAttachments:[],exceededTransferLimit:!1}))}return u}catch(e){return w.errors.set("",e),[]}})));if(w.errors.size>0)throw w;return v}