/* COPYRIGHT Esri - https://js.arcgis.com/5.0.18/LICENSE.txt */
import"../../../core/has.js";import{assert as t}from"../webgl-engine/lib/Util.js";class s{constructor(t){this.client=t,this._cancelled=!1,this.size=0,this.duration=0}}class e{constructor(t){this.typeWorkerQuota=t,this.tasks=new Array,this.numWorkers=0,this.statistics=new i}}class i{constructor(){this.requests=0,this.size=0,this.duration=0,this.speed=0}}class r{constructor(t,s,i,r){this._workerFunc=t,this._callbackFunc=s,this._maxTotalNumWorkers=i,this._totalNumWorkers=0,this._clients=r.map(t=>new e(t))}destroy(){this._clients.length=0}hasQuota(t){const s=this._clients[t];return!!s&&(this._totalNumWorkers<this._maxTotalNumWorkers||s.numWorkers+s.tasks.length<s.typeWorkerQuota)}push(t){const s=this._clients[t.client];s&&(this._totalNumWorkers<this._maxTotalNumWorkers?(s.numWorkers++,this._totalNumWorkers++,this._workerFunc(t,(t,s)=>this._taskCallback(t,s))):s.tasks.push(t))}cancel(t){this._taskFinished(t),t._cancelled=!0}_taskFinished(s){const e=this._clients[s.client];this._totalNumWorkers--,e&&(e.numWorkers--,e.statistics.requests++,e.statistics.size+=s.size||0,e.statistics.duration+=s.duration||0,e.statistics.speed=e.statistics.duration>0?e.statistics.size/e.statistics.duration:0,t(e.numWorkers>=0)),this._next()}_next(){for(const t of this._clients)if(t&&t.numWorkers<t.typeWorkerQuota&&this._processQueue(t))return;for(const t of this._clients)if(t&&this._processQueue(t))return}_processQueue(t){for(;t.tasks.length>0;)if(this._workerFunc(t.tasks.shift(),(t,s)=>this._taskCallback(t,s)))return t.numWorkers++,this._totalNumWorkers++,!0;return!1}_taskCallback(t,s){t._cancelled||(this._callbackFunc(t,s),this._taskFinished(t))}getStatsForType(t){const s=this._clients[t];return s?{quota:s.typeWorkerQuota,workers:s.numWorkers,queueSize:s.tasks.length,requestStats:s.statistics}:null}get test(){}}export{r as AsyncWorkerQueue,s as BaseTask};
