/*
All material copyright Esri, All Rights Reserved, unless otherwise specified.
See https://js.arcgis.com/5.0/esri/copyright.txt for details.
*/
import t from"../../request.js";import e from"../../core/Error.js";import i from"../../core/Logger.js";import{isArrayBuffer as s,isUint8ClampedArray as r}from"../../core/typedArrayUtil.js";import{urlToObject as a,objectToQuery as o}from"../../core/urlUtils.js";const h=1.15;class n{constructor(t,e){this._spriteSource=t,this._maxTextureSize=e,this.devicePixelRatio=1,this._spriteImageFormat="png",this._isRetina=!1,this._spritesData={},this.image=null,this.width=null,this.height=null,this.loadStatus="not-loaded","url"===t.type&&t.spriteFormat&&(this._spriteImageFormat=t.spriteFormat),t.pixelRatio&&(this.devicePixelRatio=t.pixelRatio),this.baseURL=t.spriteUrl}get spriteNames(){const t=[];for(const e in this._spritesData)t.push(e);return t.sort(),t}getSpriteInfo(t){return this._spritesData?this._spritesData[t]:null}async load(t){if(this.baseURL){this.loadStatus="loading";try{await this._loadSprites(t),this.loadStatus="loaded"}catch{this.loadStatus="failed"}}else this.loadStatus="failed"}async _loadSprites(t){this._isRetina=this.devicePixelRatio>h;const{width:s,height:r,data:a,json:o}=await this._getSpriteData(this._spriteSource,t),n=Object.keys(o);if(!n||0===n.length||!a)return this._spritesData=this.image=null,void(this.width=this.height=0);this._spritesData=o,this.width=s,this.height=r;const d=Math.max(this._maxTextureSize,4096);if(s>d||r>d){const t=`Sprite resource for style ${this.baseURL} is bigger than the maximum allowed of ${d} pixels}`;throw i.getLogger("esri.layers.support.SpriteSource").error(t),new e("SpriteSource",t)}let p;for(let e=0;e<a.length;e+=4)p=a[e+3]/255,a[e]=a[e]*p,a[e+1]=a[e+1]*p,a[e+2]=a[e+2]*p;this.image=a}async _getSpriteData(i,n){if("image"===i.type){let t,a;if(this.devicePixelRatio<h){if(!i.spriteSource1x)throw new e("SpriteSource","no image data provided for low resolution sprites!");t=i.spriteSource1x.image,a=i.spriteSource1x.json}else{if(!i.spriteSource2x)throw new e("SpriteSource","no image data provided for high resolution sprites!");t=i.spriteSource2x.image,a=i.spriteSource2x.json}return"width"in t&&"height"in t&&"data"in t&&(s(t.data)||r(t.data))?{width:t.width,height:t.height,data:new Uint8Array(t.data),json:a}:{...d(t),json:a}}const p=a(this.baseURL),l=p.query?"?"+o(p.query):"",g=this._isRetina?"@2x":"",u=`${p.path}${g}.${this._spriteImageFormat}${l}`,c=`${p.path}${g}.json${l}`,[m,S]=await Promise.all([t(c,n),t(u,{responseType:"image",...n})]);return{...d(S.data),json:m.data}}}function d(t){const e=document.createElement("canvas"),i=e.getContext("2d");e.width=t.width,e.height=t.height,i.drawImage(t,0,0,t.width,t.height);const s=i.getImageData(0,0,t.width,t.height);return{width:t.width,height:t.height,data:new Uint8Array(s.data)}}export{n as default};
