import{r as e,z as L,A as U,B as w,u as A,G as P,h as j,j as u,b as z,c as N,D as Y,a as F,H as W}from"./index.RuhrnD1v.js";import{m as q}from"./iconPosition.BnTrQB0J.js";import{c as x}from"./createDownloadLinkElement.hhAt_ffB.js";function G(M){const{disabled:l,element:n,widgetMgr:h,endpoints:t,fragmentId:B}=M,{help:T,label:v,icon:I,ignoreRerun:g,type:p,url:k,deferredFileId:r}=n,E=n.shortcut?n.shortcut:void 0,[b,f]=e.useState(!1),[i,s]=e.useState(null),{enforceDownloadInNewTab:c=!1}=e.useContext(L),{requestDeferredFile:D}=e.useContext(U);let m=w.SECONDARY;p==="primary"?m=w.PRIMARY:p==="tertiary"&&(m=w.TERTIARY);const d=e.useMemo(()=>t.buildDownloadUrl(k),[t,k]);e.useEffect(()=>{r?.length||t.checkSourceUrlResponse(d,"Download Button")},[d,t,r]);const C=e.useCallback(async()=>{if(!D||!r){s("Deferred download not properly configured");return}f(!0),s(null);try{const o=await D(r);if(o.errorMsg){s(o.errorMsg),f(!1);return}const a=t.buildDownloadUrl(o.url);t.checkSourceUrlResponse(a,"Download Button"),x({filename:"",url:a,enforceDownloadInNewTab:c}).click()}catch(o){const a=o instanceof Error?o.message:"Download failed";s(a)}finally{f(!1)}},[D,r,t,c]),S=e.useCallback(()=>{if(l)return;g||h.setTriggerValue(n,{fromUi:!0},B),!!r?.length?C():x({filename:"",url:d,enforceDownloadInNewTab:c}).click()},[l,g,h,n,B,r,C,d,c]);A({shortcut:E,disabled:l,onActivate:S});const{clear:y,restart:R}=P(()=>{s(null)},5e3,{autoStart:!1});return e.useEffect(()=>{i?R():y()},[y,i,R]),j("div",{className:"stDownloadButton","data-testid":"stDownloadButton",children:[u(F,{help:T,containerWidth:!0,children:u(z,{kind:m,size:N.SMALL,disabled:l||b,onClick:S,containerWidth:!0,children:u(Y,{icon:b?"spinner":I,iconPosition:q(n.iconPosition),label:v,shortcut:E})})}),i&&u(W,{"data-testid":"stDownloadButtonError",children:i})]})}const _=e.memo(G);export{_ as default};
