/* COPYRIGHT Esri - https://js.arcgis.com/5.1.0/LICENSE.txt */
import{createRendererExpression as e}from"../../../../../support/ArcadeExpression.js";import{callExpressionWithCursor as t}from"../../../arcade/callExpressionWithCursor.js";import{FeatureMatcher as s}from"./Matcher.js";import n from"../../../layers/support/annodime/DimensionInfo.js";import{getFontForCIMTextSymbol as i,getFontNameForCIMTextSymbol as r}from"../../../layers/support/annodime/dimensionUtils.js";import{pick as o}from"../../../layers/support/annodime/utils.js";class a extends s{constructor(e,t,s){super(),this._context=e,this._schema=t,this._expression=s,this._meshWriters=new Map,this._dimensionInfos=new Map,this._cachedGlyphsPerFont=new Map}static async fromDimensionSchema(t,s){const{spatialReference:n}=t.viewParams.tileInfo,i=await e("$feature.STYLEID",n);return new a(t,s,i)}hasArcadeDependency(){return!0}doMatch(e){const t=this._getGroupCreator(e),{groupKey:s}=t;return this._meshWriters.get(s)}async fetchResources(e,t,s,n){const i=t.metadata.outSpatialReference,r=t.getCursor();for(;r.next();){const t=this._getGroupCreator(r),{groupKey:s}=t;let o=this._meshWriters.get(s);o||(o=await t.createGroup(this._context,this._schema,e)),this._meshWriters.set(s,o);const a=`${n}_${r.getObjectId()}`;let c=this._dimensionInfos.get(a);!c&&t.analyze&&(c=await t.analyze(i,this._schema,e),c&&this._dimensionInfos.set(a,c))}}_getGroupCreator(e){const s=t(this._expression,e,{}),n={type:"dimension-feature",styleId:parseInt(s,10)};return{get groupKey(){return"Dimension:"+JSON.stringify(o(n,"styleId"))},analyze:async(t,s,i)=>{const r=e.readLegacyFeatureForDisplay();if(!r)return;const o=await this.getDimensionInfo(n.styleId,r,t,s);return o&&await this._cacheGlyphs(o,r,i),o},createGroup(e,t){const s=t.meshes[n.styleId];return e.createMeshWriters([...s.beginDimensionLine,...s.endDimensionLine,...s.beginExtensionLine,...s.endExtensionLine,...s.textPoint])}}}async getDimensionInfo(e,t,s,i){const r=i.styleCollection.find(t=>(t.iD??0)===e);if(!r)return;return await n.create(r,t,s,e=>this._getGlyphCacheForSymbol(e))}async _cacheGlyphs(e,t,s){const n=e.getTextString(t);if(!n)return;const r=await s.fetchResourceImmediate({type:"cim-rasterization-info",resource:{type:"text",textString:n||"",font:i(e.textSymbol)}});if(r&&"glyphs"in r){const t=r.glyphs;if(null!=t){const s=this._getGlyphCacheForSymbol(e.textSymbol);if(!s)return;for(const e of t)e&&!s.glyphs[e.code]&&(s.glyphs[e.code]=e)}}}_getGlyphCacheForSymbol(e){if(!e)return null;const t=r(e);let s=this._cachedGlyphsPerFont.get(t);return s||(s={type:"glyphs",glyphs:[],isRightToLeft:!1,sdfSize:24,sdfRadius:8,sdfPadding:3},this._cachedGlyphsPerFont.set(t,s)),s}cleanup(e,t,s){const n=`${s}_${t.getObjectId()}`;this._dimensionInfos.delete(n)}getAnalyzedGraphic(e){return this._dimensionInfos.get(e)||null}}export{a as DimensionMatcher};
