/* COPYRIGHT Esri - https://js.arcgis.com/1.2/LICENSE.txt */
import { _ as _prepareAttributeValue } from "./downloadUtils.js";
import * as arcade from "@arcgis/core/arcade";
import * as intl from "@arcgis/core/intl";
class PopupUtils {
  /**
   * Get the popup title that honors arcade expressions
   *
   * @param graphic selected graphic
   * @param map __esri.Map
   * @returns Promise resolving with the popup title
   * @protected
   */
  async getPopupTitle(graphic, map) {
    let attributes = {};
    for (const [key, value] of Object.entries(graphic.attributes)) {
      attributes = {
        ...attributes,
        [`{${key.toUpperCase()}}`]: value
      };
    }
    const layer = graphic.layer;
    const popupTitle = this._removeTags(layer?.popupTemplate?.title);
    if (popupTitle.includes("{expression/expr") && layer?.popupTemplate?.expressionInfos != null) {
      for (let i = 0; i < layer.popupTemplate?.expressionInfos.length; i++) {
        const info = layer.popupTemplate.expressionInfos[i];
        const profile = arcade.createArcadeProfile("popup");
        try {
          const arcadeExecutor = await arcade.createArcadeExecutor(info.expression, profile);
          const arcadeTitle = await arcadeExecutor.executeAsync({ $feature: graphic, $layer: layer, $map: map });
          if (arcadeTitle !== null || arcadeTitle !== "") {
            attributes[`{expression/${info.name}}`.toUpperCase()] = arcadeTitle;
          }
        } catch (e) {
          console.error(e);
          continue;
        }
      }
    }
    if (layer.popupTemplate?.fieldInfos) {
      layer.fields.forEach((field) => {
        const attributeValue = graphic.attributes[field.name];
        const fieldInfo = (layer?.popupTemplate?.fieldInfos || []).find((fInfo) => fInfo.fieldName.toLowerCase() === field.name.toLowerCase());
        const formattedAttributeValue = _prepareAttributeValue(attributeValue, field.type, field?.domain, fieldInfo?.format, intl);
        attributes[`{${field.name.toUpperCase()}}`] = formattedAttributeValue ?? attributeValue;
      });
    }
    return popupTitle?.replace(/{.*?}/g, (placeholder) => {
      return attributes[placeholder.toUpperCase()] != null ? attributes[placeholder.toUpperCase()] : "";
    });
  }
  /**
   * Remove any tags from the title
   *
   * @returns title string without tags
   * @protected
   */
  _removeTags(str) {
    if (str == null || str === "") {
      return "";
    }
    return str.toString().replace(/(<([^>]+)>)/gi, "");
  }
}
export {
  PopupUtils as P
};
