/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
import { c as _ } from "../../chunks/runtime.js";
import { P as w } from "../../chunks/popupUtils.js";
import { g as u, c, h as x } from "../../chunks/mapViewUtils.js";
import { u as L } from "../../chunks/useT9n.js";
import { css as I, html as l, nothing as v } from "lit";
import { createRef as f, ref as d } from "lit-html/directives/ref.js";
import { LitElement as F, createEvent as g, noShadowRoot as b, safeClassMap as E, safeStyleMap as S } from "@arcgis/lumina";
import m from "@arcgis/core/config.js";
import * as y from "@arcgis/core/symbols/support/symbolUtils.js";
import * as $ from "@arcgis/core/core/reactiveUtils.js";
const C = I`@layer{:host{display:block}.width-full{width:100%}.pagination{display:flex;justify-content:center}.notice-msg{padding:10px;width:calc(100% - 20px)}.feature-list-popup-title{font-weight:500}.feature-list-popup-title-small{font-size:small}.feature-list-popup-title-small-ellipsis{font-size:small;white-space:nowrap!important;text-overflow:ellipsis;overflow:hidden}.popup-title{padding:0 5px;word-break:break-word}.profile-img{margin:0 5px;min-width:32px}.like-container{display:flex;align-items:center;gap:5px;color:gray!important;font-style:italic}.feature-symbol{padding:0 3px;min-width:30px;display:flex;justify-content:center}.search{padding:10px;background-color:var(--calcite-color-surface-2)!important;border-block-end:1px solid var(--calcite-color-border-3)}}`;
class T extends F {
  constructor() {
    super(), this.selectedLayerId = "", this.noFeaturesFoundMsg = "", this.pageSize = 100, this.highlightOnMap = !1, this.highlightOnHover = !1, this.textSize = "large", this.showInitialLoading = !0, this.showErrorWhenNoFeatures = !1, this.showUserImageInList = !1, this.showFeatureSymbol = !1, this.applyLayerViewFilter = !1, this.showFullTitle = !0, this.filterByMapExtent = !1, this._featureItems = [], this._featuresCount = 0, this._isLoading = !1, this._searchPlaceHolder = "", this._fullTextSearchInfo = [], this._translations = L({ name: "feature-list", blocking: !0 }), this._pagination = f(), this._calciteList = f(), this._validFieldTypes = ["small-integer", "integer", "big-integer", "single", "long"], this._abbreviatedLikeCount = "", this._likeFieldAvailable = !1, this._searchExpression = "", this.featureClick = g(), this.featureSelect = g(), this.listenOn(window, "selectedLanguageUpdated", this.selectedLanguageUpdated);
  }
  static {
    this.properties = { selectedLayerId: 1, mapView: 0, noFeaturesFoundMsg: 1, pageSize: 9, highlightOnMap: 5, highlightOnHover: 5, sortingInfo: 0, whereClause: 1, textSize: 1, showInitialLoading: 5, showErrorWhenNoFeatures: 5, showUserImageInList: 5, showFeatureSymbol: 5, applyLayerViewFilter: 5, reportingOptions: 0, showFullTitle: 5, filterByMapExtent: 5, _featureItems: 16, _featuresCount: 16, _isLoading: 16, _searchPlaceHolder: 16, _fullTextSearchInfo: 16, _translations: 16 };
  }
  static {
    this.styles = C;
  }
  static {
    this.shadowRootOptions = b;
  }
  willUpdate(t) {
    t.has("selectedLayerId") && this.selectedLayerWatchHandler(), t.has("sortingInfo") && this.sortingInfoWatchHandler(), t.has("whereClause") && this.whereClauseHandler(), t.has("filterByMapExtent") && this.hasUpdated && this.filterByMapExtentWatchHandler(this.filterByMapExtent);
  }
  async selectedLayerWatchHandler() {
    this._selectedLayer = this.mapView && await u(this.mapView, this.selectedLayerId), await this.initializeFeatureItems();
  }
  async sortingInfoWatchHandler() {
    await this.initializeFeatureItems();
  }
  async whereClauseHandler() {
    await this.initializeFeatureItems();
  }
  async filterByMapExtentWatchHandler(t) {
    t ? this.initializeMapExtentFilter() : this._filterByMapExtentHandle && this._filterByMapExtentHandle.remove();
  }
  async refresh(t) {
    if (t && this._pagination.value) {
      const e = {
        target: {
          startItem: this._pagination.value.startItem
        }
      };
      await this.pageChanged(e);
    } else this._searchExpression ? await this._searchFullText() : await this.initializeFeatureItems();
  }
  async selectedLanguageUpdated(t) {
    if (this._pagination.value) {
      const e = {
        target: {
          startItem: this._pagination.value.startItem
        }
      };
      await this.pageChanged(e);
    } else
      await this.initializeFeatureItems();
  }
  async load() {
    this._isLoading = !!this.showInitialLoading, this._popupUtils = new w(), this.mapView && this.selectedLayerId && (this._selectedLayer = await u(this.mapView, this.selectedLayerId), this._getFullTextSearchInfo()), this.filterByMapExtent && this.initializeMapExtentFilter();
  }
  async loaded() {
    await this.initializeFeatureItems();
  }
  render() {
    const t = this._canShowFullTextSearch();
    return l`<calcite-panel>${t && l`<calcite-input class=search clearable icon=search @calciteInputChange=${this._searchTextChanged} .placeholder=${this._searchPlaceHolder} title type=search></calcite-input>` || ""}${this._isLoading && l`<calcite-loader label scale=m></calcite-loader>` || ""}${this.showErrorWhenNoFeatures && this._featureItems.length === 0 && !this._isLoading && l`<calcite-notice class="notice-msg" icon=feature-details kind=info open><div slot=message>${this.filterByMapExtent ? this._translations.featureErrorMsgInCurrentMapView : this.noFeaturesFoundMsg ? this.noFeaturesFoundMsg : this._translations.featureErrorMsg}</div></calcite-notice>` || ""}<calcite-list class=${E(this.textSize === "small" && !this.showFullTitle ? "overflow-hidden" : "")} label selection-appearance=border selection-mode=none ${d(this._calciteList)}>${!this._isLoading && this._featureItems.length > 0 && l`<div>${this.filterByMapExtent && this.getExtentNotice() || ""}${this._featureItems}</div>` || ""}</calcite-list>${this.pageSize && this._featuresCount > this.pageSize && l`<div class="width-full" slot=footer><calcite-pagination class="pagination" @calcitePaginationChange=${this.pageChanged} .pageSize=${this.pageSize} start-item=1 .totalItems=${this._featuresCount} ${d(this._pagination)}></calcite-pagination></div>` || ""}</calcite-panel>`;
  }
  async getWhereCondition() {
    let t = "1=1";
    if (this.whereClause && (t = this.whereClause), this._selectedLayer?.definitionExpression && (t = t + " AND " + this._selectedLayer.definitionExpression), this.applyLayerViewFilter) {
      const e = this.mapView && await c(this.mapView, this.selectedLayerId);
      e?.filter?.where && (t = t + " AND " + e.filter.where);
    }
    return t;
  }
  async initializeFeatureItems() {
    if (this._selectedLayer) {
      this._pagination.value?.goTo("start"), this._isLoading = !!this.showInitialLoading, this._featureItems = await this.queryPage(0);
      const e = {
        where: await this.getWhereCondition(),
        geometry: this.filterByMapExtent ? this.mapView?.extent : null
      };
      this._featuresCount = await this._selectedLayer?.queryFeatureCount(e), this._isLoading = !1;
    }
  }
  initializeMapExtentFilter() {
    this._filterByMapExtentHandle = $.when(() => this.mapView?.stationary, () => {
      this.initializeFeatureItems();
    }, {
      initial: !0
    });
  }
  async pageChanged(t) {
    this._isLoading = !0, this._highlightHandle && (this._highlightHandle.remove(), this._highlightHandle = void 0);
    const e = t.target.startItem - 1;
    this._featureItems = await this.queryPage(e), this._isLoading = !1;
  }
  _canShowFullTextSearch() {
    return this._selectedLayer?.capabilities?.query?.supportsFullTextSearch && this._selectedLayer.indexes.items.filter((t) => t.indexType == "FullText").length > 0;
  }
  _getFullTextSearchInfo() {
    if (this._fullTextSearchInfo = [], this._selectedLayer?.capabilities?.query?.supportsFullTextSearch) {
      const t = this._selectedLayer.indexes?.filter((e) => e.indexType == "FullText");
      if (t?.length) {
        const e = [];
        t.forEach((i) => {
          e.push(...i.fields.split(","));
        });
        const s = [];
        e.forEach((i) => {
          const a = this._selectedLayer?.getField(i.trim());
          s.push(a?.alias || "");
        }), this._searchPlaceHolder = this._translations.searchPlaceholder ? this._translations.searchPlaceholder.replace("{{field_names}}", s.join(", ")) : "", this._fullTextSearchInfo.push({
          onFields: ["*"],
          searchTerm: "",
          searchType: "prefix"
        });
      }
    }
  }
  async _searchTextChanged(t) {
    this._fullTextSearchInfo.forEach((e) => {
      e.searchTerm = t.target.value;
    }), await this._searchFullText();
  }
  async _searchFullText() {
    this._searchExpression && this._clearSearchDefinitionExpression();
    let t = [];
    if (this._fullTextSearchInfo && this._fullTextSearchInfo[0].searchTerm) {
      const e = this._selectedLayer?.createQuery();
      e && (e.fullText = this._fullTextSearchInfo, t = await this._selectedLayer?.queryObjectIds(e), await this._updateSearchDefinitionExpression(t?.length ? t : [-1]));
    }
    await this.initializeFeatureItems();
  }
  async _updateSearchDefinitionExpression(t) {
    if (this._selectedLayer) {
      const e = this._selectedLayer.definitionExpression;
      if (t?.length) {
        const s = `objectId in(${t})`;
        this._selectedLayer.definitionExpression = this._searchExpression && e && e?.indexOf(this._searchExpression) > -1 ? e.replace(this._searchExpression, s) : e ? `${e} AND (${s})` : s, this._searchExpression = s;
      } else
        this._clearSearchDefinitionExpression();
    }
  }
  _clearSearchDefinitionExpression() {
    if (this._selectedLayer) {
      const t = this._selectedLayer?.definitionExpression;
      this._searchExpression && t && t?.indexOf(this._searchExpression) > -1 && (t?.indexOf(" AND (" + this._searchExpression) > -1 ? this._selectedLayer.definitionExpression = t.replace(` AND (${this._searchExpression})`, "") : this._selectedLayer.definitionExpression = t.replace(this._searchExpression, ""));
    }
    this._searchExpression = "";
  }
  async featureClicked(t, e) {
    if (this.featureClick.emit(), this.clearHighlights(), this.highlightOnMap) {
      const s = Number(t.target.value), i = this.mapView && await c(this.mapView, this.selectedLayerId);
      this._highlightHandle = i && this.mapView ? await x([s], i, this.mapView, !0) : void 0;
    }
    await this.emitSelectedFeature(e);
  }
  async emitSelectedFeature(t) {
    const e = t.layer, s = e.createQuery();
    s.returnGeometry = !0;
    const i = Number(t.getObjectId());
    if (!Number.isNaN(i) && s) {
      s.objectIds = [i];
      const a = await e.queryFeatures(s);
      this.featureSelect.emit(a.features[0]);
    }
  }
  async onFeatureHover(t) {
    if (this.clearHighlights(), this.highlightOnHover) {
      const e = Number(t.getObjectId()), s = this.mapView && await c(this.mapView, this.selectedLayerId);
      s && (this._highlightHandle = s.highlight([e], { name: "temporary" }));
    }
  }
  clearHighlights() {
    this._highlightHandle && this._highlightHandle.remove();
  }
  async queryPage(t) {
    const e = this._selectedLayer;
    if (e) {
      const s = this.sortingInfo?.field ? this.sortingInfo.field : e.objectIdField, i = this.sortingInfo?.order ? this.sortingInfo.order : "desc", a = await this.getWhereCondition(), r = {
        start: t,
        num: this.pageSize,
        outFields: ["*"],
        returnGeometry: !0,
        where: a,
        outSpatialReference: this.mapView?.spatialReference.toJSON(),
        geometry: this.filterByMapExtent ? this.mapView?.extent : null
      };
      s && i && (r.orderByFields = [s.toString() + " " + i]);
      const n = await e.queryFeatures(r);
      return await this.createFeatureItem(n);
    } else
      return;
  }
  async createFeatureItem(t) {
    const e = t?.features, s = this.reportingOptions && this.reportingOptions[this.selectedLayerId]?.like, i = e.map(async (a) => {
      const r = this.mapView?.map && await this._popupUtils?.getPopupTitle(a, this.mapView.map) || "";
      let n, o;
      return this.showUserImageInList && this._selectedLayer?.editFieldsInfo?.creatorField && (n = await this.getUserInformation(a)), this.showFeatureSymbol && (o = await this.getFeatureSymbol(a)), s && this.getAbbreviatedLikeCount(a), this.getFeatureItem(a, r, o, n);
    });
    return Promise.all(i);
  }
  getExtentNotice() {
    return l`<calcite-notice class="notice-msg" icon=extent-filter kind=brand open scale=s><div slot=message>${this._translations.extentFilterMsg}</div></calcite-notice>`;
  }
  getAbbreviatedLikeCount(t) {
    const e = this._selectedLayer;
    if (e) {
      const s = this.reportingOptions && this.reportingOptions[e.id].likeField;
      e.fields.forEach((i) => {
        if (this._validFieldTypes.indexOf(i.type) > -1 && i.name === s && this.reportingOptions && this.reportingOptions[e.id].like) {
          this._likeFieldAvailable = !0;
          let a = t.attributes[s] || 0;
          a > 999 && this._translations.millions_value && this._translations.thousands_value && (a = a > 999999 ? this._translations.millions_value.replace("{{millions_value}}", Math.floor(a / 1e6).toString()) : this._translations.thousands_value.replace("{{thousands_value}}", Math.floor(a / 1e3).toString())), this._abbreviatedLikeCount = a;
        }
      });
    }
  }
  getFeatureItem(t, e, s, i) {
    if (this._selectedLayer?.id && this._calciteList.value) {
      const a = t.attributes[this._selectedLayer.objectIdField].toString();
      e = e ?? a;
      const r = Number(t.attributes[this.reportingOptions?.[this._selectedLayer.id].likeField || ""]).toLocaleString(), n = this.textSize === "small" && !this.showFullTitle ? "feature-list-popup-title-small-ellipsis" : this.textSize === "small" ? "feature-list-popup-title-small" : "feature-list-popup-title", o = this.showUserImageInList ? 115 : 65, p = this._calciteList.value.offsetWidth - o;
      return l`<calcite-list-item @mouseleave=${() => {
        this.clearHighlights();
      }} @mouseover=${() => {
        this.onFeatureHover(t);
      }} @calciteListItemSelect=${(h) => {
        this.featureClicked(h, t);
      }} .value=${a}>${this.showUserImageInList && l`<calcite-avatar class=profile-img .fullName=${i?.fullName} scale=m slot=content-start .thumbnail=${i?.userProfileUrl} .userId=${i?.id} .username=${i?.fullName ? i.username : void 0}></calcite-avatar>` || ""}${this.showFeatureSymbol && s && l`<div class=feature-symbol slot=content-start ${d((h) => h && h.replaceChildren(s))}></div>` || ""}<div class=${`popup-title ${n}`} slot=content-start style=${S({ maxWidth: this.textSize === "large" ? "none" : `${p}px` })}>${e}</div>${this._likeFieldAvailable && l`<div class=like-container id=${a.concat("like") ?? v} slot=content-end><span>${this._abbreviatedLikeCount}</span><calcite-icon aria-hidden=true icon=thumbs-up scale=s></calcite-icon><calcite-tooltip overlay-positioning=fixed placement=top .referenceElement=${a.concat("like")}>${r}</calcite-tooltip></div>` || ""}<calcite-icon aria-hidden=true flip-rtl icon=chevron-right scale=s slot=content-end></calcite-icon></calcite-list-item>`;
    } else
      return;
  }
  async getUserInformation(t) {
    let e = this._selectedLayer?.editFieldsInfo?.creatorField;
    if (e) {
      t.attributes.hasOwnProperty(e.toLowerCase()) ? e = e.toLowerCase() : t.attributes.hasOwnProperty(e.toUpperCase()) && (e = e.toUpperCase());
      let s = `${m.portalUrl}/sharing/rest/community/users/${t.attributes[e]}?f=json&returnUserLicensedItems=true`;
      const i = this.mapView?.map?.portalItem.portal?.credential?.token;
      i && (s += `&token=${i}`);
      const r = await (await fetch(s)).json(), n = r?.username ?? t.attributes[e];
      let o = `${m.portalUrl}/sharing/rest/community/users/${n}/info/blob.png`;
      return r?.access && i && (o += `?token=${i}`), r.userProfileUrl = o, r;
    } else
      return;
  }
  async getFeatureSymbol(t) {
    const e = document.createElement("div");
    return await y?.getDisplayedSymbol(t).then(async (s) => {
      if (s && await y?.renderPreviewHTML(s, {
        node: e
      }), e.children?.length) {
        const i = e.children[0];
        if (i) {
          const a = Number(i.getAttribute("height")), r = Number(i.getAttribute("width"));
          r > 30 && (e.setAttribute("width", "30"), i.setAttribute("width", "30")), a > 30 && (e.setAttribute("height", "30"), i.setAttribute("height", "30")), i.setAttribute("viewBox", `0 0 ${r} ${a}`), e.setAttribute("viewBox", `0 0 ${r} ${a}`);
        }
      }
    }), e;
  }
}
_("feature-list", T);
export {
  T as FeatureList
};
