/* COPYRIGHT Esri - https://js.arcgis.com/5.1.0/LICENSE.txt */
import e from"../../../../request.js";import{throwIfAborted as o}from"../../../../core/promiseUtils.js";import{join as t}from"../../../../core/urlUtils.js";import{isHostedAgolService as r}from"../../../support/arcgisLayerUrl.js";import{makeProgressManager as s,estimatedTransferTime as a}from"../../../../support/progressUtils.js";const n=1e6,i=20*n,p=2e9,l=3;async function m({data:m,name:f,description:d},u,h){let w=null;try{const y=t(u,"uploads"),j=t(y,"info"),{data:g}=await e(j,{query:{f:"json"},responseType:"json"});o(h);const q=r(u),z=g.maxUploadFileSize*n,T=q?p:z,U=q?Math.min(i,z):i;if(m.size>T)throw new Error("Data too large");const A=t(y,"register"),{data:E}=await e(A,{query:{f:"json",itemName:c(f),description:d},responseType:"json",method:"post"});if(o(h),!E.success)throw new Error("Registration failed");const{itemID:P}=E.item;w=t(y,P);const D=t(w,"uploadPart"),I=Math.ceil(m.size/U),M=new Array;for(let e=0;e<I;++e)M.push(m.slice(e*U,Math.min((e+1)*U,m.size)));const v=M.slice().reverse(),x=new Array,F=s(I,h?.onProgress,"uploadItem"),_=async()=>{for(;0!==v.length;){const t=M.length-v.length,r=v.pop(),s=new FormData,n=F.simulate(t,a(r.size));try{s.append("f","json"),s.append("file",r),s.append("partId",`${t}`);const{data:a}=await e(D,{timeout:0,body:s,responseType:"json",method:"post"});if(o(h),!a.success)throw new Error("Part upload failed")}finally{n.remove()}}};for(let e=0;e<l&&0!==v.length;++e)x.push(_());await Promise.all(x);const b=t(w,"commit"),{data:C}=await e(b,{query:{f:"json",parts:M.map((e,o)=>o).join(",")},responseType:"json",method:"post"});if(o(h),!C.success)throw new Error("Commit failed");return C.item}catch(y){if(null!=w){const o=t(w,"delete");await e(o,{query:{f:"json"},responseType:"json",method:"post"})}throw y}}function c(e){return e.replaceAll("/","_").replaceAll("\\","_")}export{m as uploadItem};
