/* COPYRIGHT Esri - https://js.arcgis.com/5.0/LICENSE.txt */
import e from"../../../../../../core/Error.js";import has from"../../../../../../core/has.js";import{isAbortError as t,throwIfAborted as r}from"../../../../../../core/promiseUtils.js";import o from"../../../../../../rest/support/QuantizationParameters.js";import{AFeatureLoadStrategy as a}from"./AFeatureLoadStrategy.js";import{FeatureSnapshotSourceChunk as s}from"./chunks/FeatureSnapshotSourceChunk.js";import{FeatureSetReaderJSON as n}from"../../support/FeatureSetReaderJSON.js";class i extends a{constructor(e,t,r){super(e,t,r)}get about(){return{willQueryAllFeatures:!0,willQueryFullResolutionGeometry:!0}}load(e){return null==this._promise&&(this._promise=this._download()),this._promise}unload(e){}async _download(){const e=this._schema.snapshotInfo.initialTolerance,t=e?new o({mode:"view",originPosition:"upper-left",tolerance:e}):null;await this._downloadStreaming(t),null!=t&&await this._downloadRefresh()}async _downloadStreaming(t){try{for await(const e of this._fetchPages(t))this.store.insert(e)}catch(r){throw new e("featurelayer-query","Encountered error when downloading data",{error:r})}}async _downloadRefresh(){try{const e=[];for await(const t of this._fetchPages(null))e.push(t);this.store.clear();for(const t of e)this.store.insert(t);this.store.refresh()}catch(t){throw new e("featurelayer-query","Encountered error when downloading data",{error:t})}}async*_fetchPages(e){let r;try{for await(const t of this._concurrentPageStream(e))0!==t.size()&&(yield t)}catch(o){r=o}if(r&&t(r)||(yield new s(n.empty(this.metadata),null,-1,!0)),r)throw r}async*_concurrentPageStream(e){const t=has("featurelayer-snapshot-concurrency"),r=this._pageStreamAll(e),o=[];let a=!1,s=1;for(;!a;){const e=[];for(;!a&&o.length<s;){const t=r.next();if(!t.value){a=!0;break}const s=t.value;s.then(e=>{e.reader.exceededTransferLimit||(a=!0)}).catch(e=>{a=!0}).finally(()=>{o.splice(o.indexOf(s),1)}),o.push(s),e.push(s)}for(const t of e)yield t;o.length&&await Promise.race(o),s<t&&(s+=1)}}*_pageStreamAll(e){const t=Math.ceil(this._schema.snapshotInfo.maxFeatureCount/this._queryInfo.pageSize);for(let r=0;r<t;r++)yield this._downloadPage(r,e)}async _downloadPage(e,t){r(this._options);const o=this._queryInfo.createPagedQuery(e,t),a=await this._fetch(o,this._options,{chunkId:e.toString()}),n=new s(a,o.inner.toJSON(),e,!1);return r(this._options),n}}export{i as FeatureSnapshotLoadStrategy};
