import{o as e}from"./chunk.DuxOD-Sk.js";import{r as t}from"./emotion-is-prop-valid.esm.DV_OErv-.js";import{c as n,l as r}from"./emotion-styled.browser.esm.BPUx6WuE.js";import{Lt as i,Q as a,Rt as o,_t as s,et as c,ft as l,ht as u,zt as d}from"./src.sR_9Xh2m.js";import{r as f}from"./UriUtil.B2jDpauP.js";import{t as p}from"./useTimeout.DBBq-Pb3.js";import{t as m}from"./createDownloadLinkElement.CYbmhmT2.js";import{t as h}from"./iconPosition.CAyE8Pjc.js";var g=e(t());function _(e){let{disabled:t,element:_,widgetMgr:v,endpoints:y,fragmentId:b}=e,{help:x,label:S,icon:C,ignoreRerun:w,type:T,url:E,deferredFileId:D}=_,O=_.shortcut?_.shortcut:void 0,[k,A]=(0,g.useState)(!1),[j,M]=(0,g.useState)(null),{enforceDownloadInNewTab:N=!1}=(0,g.useContext)(f),{requestDeferredFile:P}=(0,g.useContext)(c),F=o.SECONDARY;T===`primary`?F=o.PRIMARY:T===`tertiary`&&(F=o.TERTIARY);let I=(0,g.useMemo)(()=>y.buildDownloadUrl(E),[y,E]);(0,g.useEffect)(()=>{D?.length||y.checkSourceUrlResponse(I,`Download Button`)},[I,y,D]);let L=(0,g.useCallback)(async()=>{if(!P||!D){M(`Deferred download not properly configured`);return}A(!0),M(null);try{let e=await P(D);if(e.errorMsg){M(e.errorMsg),A(!1);return}let t=y.buildDownloadUrl(e.url);y.checkSourceUrlResponse(t,`Download Button`),m({filename:``,url:t,enforceDownloadInNewTab:N}).click()}catch(e){M(e instanceof Error?e.message:`Download failed`)}finally{A(!1)}},[P,D,y,N]),R=(0,g.useCallback)(()=>{t||(w||v.setTriggerValue(_,{fromUi:!0},b),D?.length?L():m({filename:``,url:I,enforceDownloadInNewTab:N}).click())},[t,w,v,_,b,D,L,I,N]);u({shortcut:O,disabled:t,onActivate:R});let{clear:z,restart:B}=p(()=>{M(null)},5e3,{autoStart:!1});return(0,g.useEffect)(()=>{j?B():z()},[z,j,B]),r(`div`,{className:`stDownloadButton`,"data-testid":`stDownloadButton`,children:[n(s,{help:x,containerWidth:!0,children:n(i,{kind:F,size:d.SMALL,disabled:t||k,onClick:R,containerWidth:!0,children:n(l,{icon:k?`spinner`:C,iconPosition:h(_.iconPosition),label:S,shortcut:O})})}),j&&n(a,{"data-testid":`stDownloadButtonError`,children:j})]})}var v=(0,g.memo)(_);export{v as default};