/* COPYRIGHT Esri - https://js.arcgis.com/5.0.18/LICENSE.txt */
import{__addDisposableResource as t,__disposeResources as r}from"tslib";import e from"../../../Graphic.js";import{Feature as a}from"../../Feature.js";import{AsyncMutex as s}from"../../../core/asyncUtils.js";class i{constructor(t,r){this._parent=t,this._abortSignal=r,this._done=!1,this._features=null,this._batchMutex=new s,this._currentPage=null,this._pageCursor=-1}get _numAvailable(){return null==this._currentPage||this._pageCursor<0?0:Math.max(this._currentPage.length-this._pageCursor,0)}_takeNFeatures(t){if(null==this._currentPage)return[];const r=this._currentPage.slice(this._pageCursor,this._pageCursor+t);return this._pageCursor+=r.length,r.map(t=>e.fromJSON(t))}_takeOneFeature(){const t=this._currentPage[this._pageCursor];return this._pageCursor+=1,e.fromJSON(t)}async _nextBatch(){if(this._done)return!1;const t=await(this._features??=this._parent.queryAll(this._abortSignal));let r;do{if(r=await t.next(),r.done)return this._done=!0,this._currentPage=null,this._pageCursor=-1,!1}while(r.value.length<=0);return this._currentPage=r.value,this._pageCursor=0,!0}async nextBatchAsArcadeFeatures(t,r){const e=await this.nextBatch(t);return null==e?e:e.map(t=>a.createFromGraphicLikeObject(t.geometry,t.attributes,this._parent,r))}async nextBatch(e){const a={stack:[],error:void 0,hasError:!1};try{if(this._done)return null;if(e<=0)return[];t(a,await this._batchMutex.acquire(),!1);if(this._numAvailable>=e)return this._takeNFeatures(e);const r=[];let s=e;do{const t=this._takeNFeatures(s);s-=t.length,r.push(t)}while(s>0&&await this._nextBatch());const i=r.flat();return i.length>0?i:null}catch(s){a.error=s,a.hasError=!0}finally{r(a)}}async next(){const e={stack:[],error:void 0,hasError:!1};try{if(this._done)return null;t(e,await this._batchMutex.acquire(),!1);return this._numAvailable>=1||await this._nextBatch()?this._takeOneFeature():null}catch(a){e.error=a,e.hasError=!0}finally{r(e)}}}export{i as QueryIterator};
