/* COPYRIGHT Esri - https://js.arcgis.com/5.1.0/LICENSE.txt */
import{__addDisposableResource as t,__disposeResources as e}from"tslib";import a from"../../../../request.js";import s from"../../../../core/Error.js";import{EventEmitter as r}from"../../../../core/Evented.js";import has from"../../../../core/has.js";import{QueueProcessor as n}from"../../../../core/QueueProcessor.js";import{isBlobProtocol as i}from"../../../../core/urlUtils.js";import{ParquetFileInfo as o}from"./ParquetFileInfo.js";import{parseFileStatisticsMap as c}from"./ParquetFileStatistics.js";import{createParquetFile as h,readMetadata as u}from"../../../../libs/parquet/parquet.js";const f="parquet.v1",l="_spatial.json",g=new n({concurrency:12,process:async t=>{const{data:e}=await a(t.url,t.options);return e}});class p{constructor(t,e=()=>{}){this._geometryInfo=t,this._getCustomParameters=e,this.events=new r}async destroy(){await this.clear()}async clear(){if(this._infos){const t=await this._infos;for(const e of t.values())e.destroy();t.clear(),this._infos=null}}async getMetadata(){const a={stack:[],error:void 0,hasError:!1};try{const e=(await this._getParquetFileNames()).at(0);if(!e)return null;const s=t(a,await h(e,{provider:this}),!1);return u(s)}catch(s){a.error=s,a.hasError=!0}finally{e(a)}}getGeometryInfo(){return this._geometryInfo}async getFiles(){const t=await this._getInfoMap();return Array.from(t.values())}async updateGeometryInfo(t){if(this._geometryInfo)throw new Error("GeometryInfo already set");await this.clear(),this._geometryInfo=t}async fetchLength(t){const{byteLength:e,cacheTag:a}=await this._fetchLengthAndTag(t);if(!has("parquetlayer-cache-enabled"))return e;try{await this._createOrResetCache(t,a)}catch(s){}return e}async fetchRange(t,e,a,s){if(!has("parquetlayer-cache-enabled"))return this._fetchRange(t,e,a,s);const r=new URL(this._getCacheFileName(t));r.searchParams.append("range",`${e}-${a}`);try{const n=await this._openCache(t),i=await n.match(r);if(i)return await i.arrayBuffer();const o=await this._fetchRange(t,e,a,s);return await n.put(r,new Response(o,{headers:{"Content-Type":"application/octet-stream","Content-Length":o.byteLength.toString()}})),o}catch(n){return this._fetchRange(t,e,a,s)}}_getCacheFileName(t){return t}async _requestStatistics(t){const{data:e}=await a(t,{responseType:"json",query:this._getCustomParameters()});return e}async _fetchRange(t,e,a,r){const n={url:t,options:{responseType:"array-buffer",query:this._getCustomParameters()??{},cacheMode:"no-store",useQueue:!0,headers:{range:`bytes=${e}-${a}`}}},i=await g.push(n),o=a-e+1;if(i.byteLength!==o)throw new s("InvalidRangeRequest",`request returned ${i.byteLength} bytes for range ${e}-${a}, expected ${o}.`);return i}async _fetchLengthAndTag(t){if(i(t)){const{data:e}=await a(t,{responseType:"blob"});return{byteLength:e.size,cacheTag:null}}const e=await this._requestHead(t),s=e.headers.get("Content-Length");if(null==s)throw new Error("Unable to parse content length");const r=e.headers.get("etag")??e.headers.get("Last-Modified");return{byteLength:parseInt(s,10),cacheTag:r}}async _getInfoMap(){return this._infos||(this._infos=this._fetchParquetFiles()),this._infos}async _updateParquetFileInfos(t){const e=await this._getInfoMap(),a=new Set(t);for(const s of a)if(!e.get(s)){const t=e.size,a=await o.create(this.getGeometryInfo(),this,s,t,null);e.set(s,a)}for(const s of e.keys())if(!a.has(s))throw new Error("Deletion not supported")}async _getFileStatistics(t){this._statistics||(this._statistics=this._fetchStatistics());const e=await this._statistics,a=m(t);return e.get(a)}async _fetchParquetFiles(){const t=(await this._getParquetFileNames()).map(async(t,e)=>{const a=e,s=await this._getFileStatistics(t);return o.create(this.getGeometryInfo(),this,t,a,s)}),e=await Promise.all(t),a=new Map;for(const s of e)a.set(s.url,s);return a}async _fetchStatistics(){const t=await this._getStatisticsFileName();if(null==t)return new Map;const e=await this._resolveFileUrl(t),a=await this._requestStatistics(e);return c(a)}async _requestHead(t){const{data:e}=await a(t,{responseType:"native",method:"head",query:this._getCustomParameters()});return e}async _openCache(t){return caches.open(this._getCacheName(t))}_getCacheName(t){return`${f}:${this._getCacheFileName(t)}`}async _createOrResetCache(t,e){const a=this._getCacheName(t),s=new URL(this._getCacheFileName(t));if(s.searchParams.append("metadata","true"),null==e)return void await caches.delete(a);let r=await caches.open(a);const n=await r.match(s),i=await(n?.json());i?.tag!==e&&(await caches.delete(a),r=await caches.open(a));const o=JSON.stringify({tag:e});await r.put(s,new Response(o,{headers:{"Content-Type":"application/json","Content-Length":o.length.toString()}}))}}function y(t){const e=t.split(/[?#]/)[0];return e===l||e.endsWith(l)}function m(t){return t.split(/[?#]/)[0].split("/").at(-1)??t}export{p as FileProvider,y as isStatisticsFileName,l as spatialFileName};
