/* COPYRIGHT Esri - https://js.arcgis.com/5.1.2/LICENSE.txt */
import{nextTick as e}from"./nextTick.js";import{recordPerformance as t}from"./performance.js";import n from"./PerformanceSampler.js";import r from"./PooledArray.js";import{isAborted as s,createAbortError as o}from"./promiseUtils.js";import{Milliseconds as i}from"./time.js";class a{constructor(e){this.phases=e,this.paused=!1,this.ticks=-1,this.removed=!1}}class c{constructor(e){this.callback=e,this.isActive=!0}remove(){this.isActive=!1}}let m=0,l=0;const u={time:i(0),deltaTime:i(0),elapsedFrameTime:i(0),frameDuration:i(0)},p=["prepare","preRender","render","postRender","update","finish"],f=[],h=new r;class d{constructor(e){this._task=e}remove(){this._task.removed=!0}pause(){this._task.paused=!0}resume(){this._task.paused=!1,v()}}function w(){null!=T&&(cancelAnimationFrame(T),T=requestAnimationFrame(x))}function v(){null==T&&(m=performance.now(),T=requestAnimationFrame(x))}const k={frameTasks:h,willDispatch:!1,clearFrameTasks:D,dispatch:S,executeFrameTasks:g,reschedule:w};function A(t){const n=new c(t);return f.push(n),k.willDispatch||(k.willDispatch=!0,e(S)),n}function F(e){const t=new a(e);return h.push(t),v(),new d(t)}let T=null;function D(e=!1){h.forAll(e=>{e.removed=!0}),e&&P()}function j(e){l=Math.max(0,e)}function x(){const e=performance.now();T=null;const t=h.some(e=>!e.paused&&!e.removed);T=t?requestAnimationFrame(x):null,k.executeFrameTasks(e)}function g(e){const n=i(e-m);m=e;const r=l>0?l:1e3/60,s=Math.max(0,n-r);u.time=e,u.frameDuration=i(r-s);for(let a=0;a<p.length;a++){const r=performance.now(),s=p[a];h.forAll(t=>{if(t.paused||t.removed)return;0===a&&t.ticks++;t.phases[s]&&(u.elapsedFrameTime=i(performance.now()-e),u.deltaTime=0===t.ticks?i(0):n,t.phases[s]?.call(t,u))});const o=performance.now();K[a].push(o-r),t(s,r,o,"Maps SDK","Scheduling")}P();const o=performance.now();U.push(o-e),t("Animation Frame",e,o,"Maps SDK","Scheduling")}const M=new r;function P(){h.forAll(e=>{e.removed&&M.push(e)}),h.removeUnorderedMany(M.data,M.length),M.clear()}function R(){h.prune(),M.prune()}function S(){for(;f.length;){const e=f.shift();e.isActive&&e.callback()}k.willDispatch=!1}function q(t=1,n){const r=Promise.withResolvers(),i=()=>{s(n)?r.reject(o()):0===t?r.resolve():(--t,e(()=>i()))};return i(),r.promise}function _(e){return q(1,e)}function b(){const e=Promise.withResolvers(),t=F({postRender:()=>{t.remove(),A(()=>e.resolve())}});return e.promise}async function y(e){await _(e),await new Promise(t=>requestAnimationFrame(()=>{e?.aborted||t()}))}const K=p.map(e=>new n(e)),U=new n("total");export{F as addFrameTask,R as cleanupScheduling,k as debug,K as performanceInfo,U as performanceTotal,A as schedule,j as setFrameDuration,y as waitAnimationFrame,b as waitRender,_ as waitTick,q as waitTicks};
