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