/*
All material copyright Esri, All Rights Reserved, unless otherwise specified.
See https://js.arcgis.com/5.0/esri/copyright.txt for details.
*/
import{handlesGroup as t}from"../../../../../../core/handleUtils.js";import has from"../../../../../../core/has.js";import{throwIfAborted as e,onAbort as s}from"../../../../../../core/promiseUtils.js";import{AFeatureTileLoadStrategy as o}from"./AFeatureTileLoadStrategy.js";import{DrillDownTileSourceChunk as r}from"./chunks/DrillDownTileSourceChunk.js";import{FeatureSetReaderJSON as i}from"../../support/FeatureSetReaderJSON.js";const a=has("featurelayer-query-max-depth");class l{constructor(e,o){this.subscription=e,this._tileIdToResult=new Map,this._controller=new AbortController,this._handles=t([s(e.signal,()=>this._controller.abort()),s(o,()=>this._controller.abort())])}destroy(){this._controller.abort(),this._handles.remove()}get(t){return this._tileIdToResult.get(t)}set(t,e){this._tileIdToResult.set(t,e)}get options(){return{signal:this._controller.signal}}}class n extends o{constructor(){super(...arguments),this._loadStates=new Map}destroy(){super.destroy();for(const t of this._loadStates.values())t.destroy();this._loadStates.clear()}get about(){return{willQueryAllFeatures:!1,willQueryFullResolutionGeometry:!1}}async load(t){this._loadStates.has(t.key.id)||this._loadStates.set(t.key.id,new l(t,this._options));const s=this._loadStates.get(t.key.id);let o;try{for await(const o of this._fetchChunkInfos(s,t.tile,0)){const{queryJSON:t,reader:i,sourceTile:a,sourceTileDepth:l,tile:n}=o,h=new r(i,t,n,a,l,!1);e(s.options),this._addChunk(h)}}catch(n){o=n}e(s.options);const a=new r(i.empty(this.metadata),null,t.tile,null,-1,!0);if(this._addChunk(a),o)throw o}unload(t){super.unload(t),this._loadStates.get(t.key.id)?.destroy(),this._loadStates.delete(t.key.id)}async*_fetchChunkInfos(t,e,s){let o=t.get(e.id);const r=!!o;if(o||(o=await this._fetchChunkInfo(t,e,s),t.set(e.id,o)),o.reader.exceededTransferLimit&&s<has("featurelayer-query-max-depth"))for(const i of e.createChildTiles())yield*this._fetchChunkInfos(t,i,s+1);else r||(yield o)}async _fetchChunkInfo(t,e,s){const o=t.subscription.tile.getQuantizationParameters(),r=this._queryInfo.createTileQuery(e,{returnExceededLimitFeatures:s===a,quantizationParameters:o});return{reader:await this._fetch(r,t.options,{chunkId:e.id}),queryJSON:r.inner.toJSON(),tile:t.subscription.tile,sourceTile:e,sourceTileDepth:s}}}export{n as FeatureDrillDownTileLoadStrategy};
