/* COPYRIGHT Esri - https://js.arcgis.com/5.1.0/LICENSE.txt */
import{handlesGroup as e}from"../../../../../../core/handleUtils.js";import has from"../../../../../../core/has.js";import{getOrCreateMapValue as t}from"../../../../../../core/MapUtils.js";import{throwIfAborted as o,isAbortError as s,onAbort as r}from"../../../../../../core/promiseUtils.js";import{AFeatureTileLoadStrategy as a}from"./AFeatureTileLoadStrategy.js";import{PagedTileSourceChunk as i}from"./chunks/PagedTileSourceChunk.js";import{FeatureSetReaderJSON as n}from"../../support/FeatureSetReaderJSON.js";class l{constructor(t,o){this.subscription=t,this._pages=new Set,this._controller=new AbortController,this._done=!1,this._handles=e([r(t.signal,()=>this._controller.abort()),r(o,()=>this._controller.abort())])}destroy(){this._controller.abort(),this._handles.remove()}get pageStart(){let e=-1;for(const t of this._pages.values())e=Math.max(e,t);return e+1}get done(){return this._done}get options(){return{signal:this._controller.signal}}add(e,t){this._pages.add(e),this._done=this._done||t}}class c extends a{constructor(){super(...arguments),this._loadStates=new Map}destroy(){super.destroy();for(const e of this._loadStates.values())e.destroy();this._loadStates.clear()}get about(){return{willQueryAllFeatures:!1,willQueryFullResolutionGeometry:!1}}async load(e){const o=t(this._loadStates,e.key.id,()=>new l(e,this._options));for await(const t of this._fetchPages(o))this._addChunk(t)}unload(e){super.unload(e),this._loadStates.get(e.key.id)?.destroy(),this._loadStates.delete(e.key.id)}async*_fetchPages(e){let t;try{for await(const t of this._concurrentPageStream(e))o(e.options),0!==t.size()&&(yield t)}catch(r){t=r}if(t&&s(t)||(yield new i(n.empty(this.metadata),null,e.subscription.tile,-1,!0)),t)throw t}async*_concurrentPageStream(e){const t=has("featurelayer-query-tile-concurrency"),o=this._pageStreamAll(e),s=[];let r=!1,a=1;for(;!r;){const e=[];for(;!r&&s.length<a;){const t=o.next();if(!t.value){r=!0;break}const a=t.value;a.then(e=>{e.reader.exceededTransferLimit||(r=!0)}).catch(e=>{r=!0}).finally(()=>{s.splice(s.indexOf(a),1)}),s.push(a),e.push(a)}for(const t of e)yield t;s.length&&await Promise.race(s),a<t&&(a+=1)}}*_pageStreamAll(e){const t=Math.ceil(has("featurelayer-query-tile-max-features")/this._queryInfo.getPageSize(!0));for(let o=0;o<t;o++)yield this._downloadPage(o,e)}async _downloadPage(e,t){o(t.options);const s=t.subscription.tile,r=this._queryInfo.createPagedTileQuery(s,e),a=await this._fetch(r,t.options,{chunkId:`${s.id}-${e}`});return o(t.options),new i(a,r.inner.toJSON(),s,e,!1)}}export{c as FeaturePagedTileLoadStrategy};
