/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
import { c as E } from "../../chunks/runtime.js";
import { e as I, g as T, c as v } from "../../chunks/mapViewUtils.js";
import { b as F } from "../../chunks/queryUtils.js";
import { d as x } from "../../chunks/downloadUtils.js";
import { b as g } from "../../chunks/interfaces.js";
import { defineCustomElements as S } from "@arcgis/instant-apps-components/loader";
import { u as O } from "../../chunks/useT9n.js";
import { css as C, html as c, nothing as u } from "lit";
import { createRef as y, ref as b } from "lit-html/directives/ref.js";
import { LitElement as A, createEvent as o, noShadowRoot as H, safeClassMap as m } from "@arcgis/lumina";
import { f as L } from "../../chunks/helpers.js";
import $ from "@arcgis/core/widgets/FeatureTable.js";
import * as p from "@arcgis/core/core/reactiveUtils.js";
import D from "@arcgis/core/rest/support/RelationshipQuery.js";
import w from "@arcgis/core/widgets/FeatureTable/support/TableTemplate.js";
const M = C`@layer{:host{display:block}.height-full{height:100%}.height-full-adjusted{height:calc(100% - 20px)}.width-full{width:100%}.display-flex{display:flex}.display-none{display:none}.table-border{border:1px solid var(--calcite-color-border-2)}.border-end{border-inline-end:1px solid var(--calcite-color-border-2)}.border-bottom{border-bottom:1px solid var(--calcite-color-border-2)}.padding-5{padding:5px}.padding-end-1{padding-inline-end:1rem}.height-51-px{height:51px}.height-50-px{height:50px}.bottom-left{position:absolute;left:0;bottom:0;padding-left:5px}html[dir=rtl] .bottom-left{position:absolute;right:0;bottom:0;padding-right:5px}.height-19{height:19px}.background{background-color:var(--calcite-color-surface-1)}.text-color{color:var(--calcite-color-text-1)}.align-center{align-items:center}.danger-color{color:var(--calcite-color-status-danger)}.esri-feature-table vaadin-grid{border:none!important}vaadin-grid-cell-content{font-size:14px!important;color:var(--calcite-color-text-3)!important}.absolute-right{position:absolute;right:0;left:unset}html[dir=rtl] .absolute-right{left:0;right:unset}.disabled{cursor:default!important;user-select:none;opacity:var(--calcite-opacity-disabled);pointer-events:none}.actions-end{height:50px!important;display:inline-flex}.border-top{border-top:1px solid var(--calcite-color-border-2)}.modal{--calcite-dialog-content-space: 0}.esri-feature-table__table-container{height:100%}.search-container{background-color:var(--calcite-color-surface-2)!important}.search{--calcite-color-border-input: var(--calcite-color-border-3);width:60%;padding:10px}.delete-red{--calcite-icon-color: var(--calcite-color-status-danger);--calcite-color-text-1: var(--calcite-color-status-danger);--calcite-color-text-3: var(--calcite-color-status-danger)}.label-override{white-space:nowrap}.padding-start-1-4{padding-inline-start:.5rem}.panel-header-override{--calcite-panel-header-content-space: 0px}.danger-label-color{color:var(--calcite-color-status-danger)}.danger-icon-color{--calcite-icon-color: var(--calcite-color-status-danger)}.width-51{width:51px}.height-51{height:51px}calcite-action-bar{--calcite-internal-action-bar-gap: 0px;--calcite-internal-action-bar-padding: 0px}}`;
class k extends A {
  constructor() {
    super(), this.defaultGlobalId = [], this.defaultLayerId = "", this.defaultOid = [], this.enableAutoRefresh = !1, this.enableColumnReorder = !0, this.enableCSV = !1, this.enableInlineEdit = !1, this.enableShare = !1, this.enableTableAutosave = !0, this.featureSelectionMode = "multiple", this.selectedRelatedIds = [], this.honorMapFieldSettings = !1, this.isMobile = !1, this.mapHidden = !1, this.showOnlyUpdatableLayers = !1, this.selectedIds = [], this.shareIncludeEmbed = !1, this.shareIncludeSocial = !1, this.showNewestFirst = !1, this.zoomAndScrollToSelected = !1, this.pasteEnabled = !1, this.showCopyPasteActions = !1, this.layerIds = [], this._allIds = [], this._configLayerOrderDefined = !1, this._csvExporting = !1, this._fetchingData = !1, this._hideTable = !1, this._filterActive = !1, this._selectAllActive = !1, this._showHideOpen = !1, this._showOnlySelected = !1, this._toolInfos = [], this._translations = O({ name: "layer-table", blocking: !0 }), this._fullTextSearchInfo = [], this._searchPlaceHolder = "", this._size = 0, this._queryingData = !1, this._editEnabled = !1, this._enabledLayerIds = [], this._defaultGlobalIdHonored = !1, this._defaultOidHonored = !1, this._deleteEnabled = !1, this._floorExpression = "", this._floorField = "", this._floorLevel = "", this._loaded = !1, this._shareNode = y(), this._toolbar = y(), this._searchExpression = "", this._skipEditCheck = !1, this._tempSelectedIds = [], this._outOFExtentOids = [], this._shouldUpdateTableOnExtentChange = !0, this._creatingFeature = !1, this._searchNode = y(), this._layerEditsHandles = [], this._pastedFeaturesIds = [], this._shouldSelectCreatedFeatures = !1, this.columnReorder = o(), this.featureSelectionChange = o(), this.toggleFilter = o(), this.showDelete = o(), this.relatedRecordToggled = o(), this.editMultipleFeatures = o(), this.copyFeatures = o(), this.pasteFeatures = o(), this.featuresAdded = o(), this.initCreateComponent = o(), this.requestLayerSelectionChange = o(), this.beforeFeatureSelectionChange = o(), this.continueEditing = o(), this.createFeatureEditorInitialized = (e) => {
      this._createFeatureEditor = e.detail;
    }, this.createFeatureEditorClosed = () => {
      this._createFeatureEditor = void 0;
    }, this.listenOn(window, "beforeMapInfoChange", this.beforeMapInfoChange, { capture: !0 }), this.listenOn(window, "editorInitialized", this.editorInitialized), this.listenOn(window, "createFeatureEditorInitialized", this.createFeatureEditorInitialized), this.listenOn(window, "createFeatureEditorClosed", this.createFeatureEditorClosed), this.listenOn(window, "closeEdit", this.closeEdit), this.listenOn(window, "selectionChanged", this.selectionChanged), this.listenOn(window, "beforeLayerSelectionChange", this.beforeLayerSelectionChange), this.listenOn(window, "layerSelectionChange", this.layerSelectionChange), this.listenOn(window, "editsComplete", this.editsComplete), this.listenOn(window, "facilityChanged", this.facilityChanged), this.listenOn(window, "levelChanged", this.levelChanged), this.listenOn(window, "siteChanged", this.siteChanged), this.listenOn(window, "noLayersFound", this.noLayersFound), this.listenOn(window, "clearSelection", this.clearSelection), this.listenOn(window, "mapChanged", this.mapChanged), this.listenOn(window, "featuresSelected", this.featuresSelected), this.listenOn(window, "createWorkFlowStarted", this.createWorkFlowStarted), this.listenOn(window, "backFromCreateWorkFlow", this.backFromCreateWorkFlow), this.listenOn(window, "pasteFeatures", this._pasteFeatures), this.listenOn(window, "featuresPasted", this._featuresPasted), S(window);
  }
  static {
    this.properties = { appLayout: 1, defaultGlobalId: 0, defaultLayerId: 1, defaultOid: 0, enableAutoRefresh: 5, enableColumnReorder: 5, enableCSV: 5, enableInlineEdit: 5, enableShare: 5, enableTableAutosave: 5, featureSelectionMode: 1, selectedRelatedIds: 0, honorMapFieldSettings: 5, isMobile: 5, mapHidden: 5, mapInfo: 0, mapView: 0, showOnlyUpdatableLayers: 5, selectedIds: 0, shareIncludeEmbed: 5, shareIncludeSocial: 5, showNewestFirst: 5, zoomAndScrollToSelected: 5, zoomToScale: 9, pasteEnabled: 5, showCopyPasteActions: 5, layerIds: 0, _allIds: 16, _configLayerOrderDefined: 16, _csvExporting: 16, _fetchingData: 16, _hideTable: 16, _filterActive: 16, _layer: 16, _selectAllActive: 16, _showHideOpen: 16, _showOnlySelected: 16, _toolInfos: 16, _translations: 16, _fullTextSearchInfo: 16, _searchPlaceHolder: 16, _size: 16, _queryingData: 16 };
  }
  static {
    this.styles = M;
  }
  static {
    this.shadowRootOptions = H;
  }
  willUpdate(e) {
    if (e.has("appLayout") && this.appLayoutWatchHandler(), e.has("defaultOid") && this.defaultOidWatchHandler(), e.has("defaultGlobalId") && this.defaultGlobalIdWatchHandler(), e.has("enableCSV") && this.enableCSVWatchHandler(), e.has("enableInlineEdit") && this.enableInlineEditWatchHandler(), e.has("mapHidden") && this.mapHiddenWatchHandler(), e.has("isMobile") && this.isMobileWatchHandler(), e.has("mapInfo") && this.mapInfoWatchHandler(), e.has("mapView") && this.mapViewWatchHandler(), e.has("_layer") && this._layerWatchHandler(), e.has("selectedIds") && (this.hasUpdated || JSON.stringify(e.get("selectedIds")) !== JSON.stringify(this.selectedIds)) && this.selectedIdsWatchHandler(), e.has("selectedRelatedIds") && (this.hasUpdated || JSON.stringify(e.get("selectedRelatedIds")) !== JSON.stringify(this.selectedRelatedIds)) && this.selectedRelatedIdsWatchHandler(), e.has("enableTableAutosave") && this.hasUpdated && this._table && (this._table.autoSaveEnabled = this.enableTableAutosave), e.has("_translations")) {
      const t = this._translations._lang, i = e.get("_translations")?._lang;
      t && i && t !== i && this._initToolInfos();
    }
    if (e.has("pasteEnabled") && this.hasUpdated) {
      const t = this._toolInfos.find((i) => i.icon === "paste-with-attribute");
      t && (t.disabled = !this.pasteEnabled);
    }
    e.has("layerIds") && this.hasUpdated && this._addListenersForLayers();
  }
  async appLayoutWatchHandler() {
    await this._initToolInfos(), this._updateShareUrl();
  }
  async defaultOidWatchHandler() {
    await this._handleDefaults();
  }
  async defaultGlobalIdWatchHandler() {
    await this._handleDefaults();
  }
  async enableCSVWatchHandler() {
    this._toolInfos?.length > 0 && await this._initToolInfos();
  }
  enableInlineEditWatchHandler() {
    this._table && (this._table.editingEnabled = this._editEnabled && this.enableInlineEdit);
  }
  async mapHiddenWatchHandler() {
    this._toolInfos?.length > 0 && await this._initToolInfos();
  }
  async isMobileWatchHandler() {
    !this._toolInfos && !this.isMobile && await this._initToolInfos();
  }
  async mapInfoWatchHandler() {
    this._configLayerOrderDefined = "configLayerOrder" in (this.mapInfo?.layerOptions || {}), this._enabledLayerIds = L(this.mapInfo?.layerOptions?.layers || [], this.mapInfo?.layerOptions?.configLayerOrder), this._table && (this._resetColumnTemplates(), this._sortTable(), await this._initToolInfos());
  }
  async mapViewWatchHandler() {
    this._mapClickHandle && this._mapClickHandle.remove(), this.mapView && (this._floorExpression = "", this._searchExpression = "", this.mapView.highlights = [
      {
        name: "default",
        color: "#00FFFF"
      },
      {
        name: "current-selection",
        color: "#ff00ff"
      },
      {
        name: "temporary",
        color: "#FFFF00"
      }
    ], this._updateShareUrl(), this._mapClickHandle = p.on(() => this.mapView, "click", (e) => {
      this._creatingFeature || this._mapClicked(e);
    }));
  }
  async _layerWatchHandler() {
    if (this._hideTable = !1, this._fetchingData = !0, !this._layer) {
      this._fetchingData = !1, this._hideTable = !0;
      return;
    }
    try {
      await this._layer.when(), this._floorField = this._layer.floorInfo?.floorField || "", this._updateFloorDefinitionExpression(), await this._resetTable(), this._updateShareUrl();
    } catch (e) {
      console.error(e), this._hideTable = !0;
    } finally {
      this._fetchingData = !1;
    }
  }
  async selectedIdsWatchHandler() {
    this._updateShareUrl(), this._validateEnabledActions(), this._selectAllActive && this.selectedIds.length !== this._allIds.length && (this._selectAllActive = !1), this.selectedIds.length > 0 && (this._table.rowHighlightIds.removeAll(), this._table.rowHighlightIds.add(this.selectedIds[0])), this.selectedIds.length === 0 && setTimeout(() => {
      this.featureSelectionChange.emit(this.selectedIds);
    }, 700);
  }
  async selectedRelatedIdsWatchHandler() {
    this._validateEnabledActions(), this.selectedRelatedIds.length > 0 && (this._relatedFeatureTable?.rowHighlightIds.removeAll(), this._relatedFeatureTable?.rowHighlightIds.add(this.selectedRelatedIds[0]));
  }
  async closeFilter() {
    await this._closeFilter();
  }
  async filterReset() {
    this._filterByExtentHandle && (this._table && (this._table.filterGeometry = void 0), this._filterByExtentHandle.remove(), this._filterByExtentHandle = void 0), await this._handleFilterListReset();
  }
  async filterUpdate(e, t) {
    await this._handleFilterUpdate(e), t ? (this._shouldUpdateTableOnExtentChange = !0, this._handleTableOnMapExtent()) : t === !1 && (this._table && (this._table.filterGeometry = void 0), this._filterByExtentHandle?.remove(), this._filterByExtentHandle = void 0, await this._updateAllIds());
  }
  async validateTableUpdate(e) {
    this._shouldUpdateTableOnExtentChange = e;
  }
  async validateActiveEdits() {
    return this._validateActiveEdits([], this.selectedIds);
  }
  async refresh() {
    this._table && await this._refresh();
  }
  async setColumnOrder(e) {
    this._setColumnTemplates(e);
  }
  async beforeMapInfoChange(e) {
    const t = e.detail.ref, i = e.detail.mapInfo;
    if (this._hasPendingEdits()) {
      e.preventDefault(), this._skipEditCheck = !1;
      const a = await this._validateActiveEdits([], this.selectedIds);
      await t.setMapByID(a ? i.id : e.detail.currentId, !a);
    }
  }
  async editorInitialized(e) {
    this._shouldUpdateTableOnExtentChange = !1, this._editor = e.detail;
  }
  async closeEdit() {
    this._shouldUpdateTableOnExtentChange = !0, this._filterByExtentHandle && this._handleTableOnMapExtent(), this._editor = void 0;
  }
  async selectionChanged(e) {
    const t = e.detail.selectedFeature[0], i = Number(t.getObjectId()), s = this._table;
    if (s.rowHighlightIds.length && s.rowHighlightIds.removeAll(), s.rowHighlightIds.add(i), this._highlightFeatures(i), this.zoomAndScrollToSelected && s && this.mapView) {
      const a = s.viewModel.getObjectIdIndex(i);
      s.scrollToIndex(a);
      const l = t.layer, h = this.mapView.allLayerViews.toArray();
      let r;
      h.some(async (n) => n.layer.title === l?.title && n.layer.type === "feature" ? (r = n, this.mapView && await I([i], r, this.mapView, !0, void 0, this.zoomToScale), !0) : !1);
    }
  }
  async beforeLayerSelectionChange(e) {
    if (this._hasPendingEdits()) {
      e.preventDefault();
      const i = e.detail.ref;
      this._skipEditCheck = !1;
      const s = await this._validateActiveEdits([], this.selectedIds);
      return e.detail.selectedIds ? await i.setLayerByIds(s ? e.detail.newIds : e.detail.currentIds, !0) : await i.setLayerById(s ? e.detail.newId : e.detail.currentId, !0);
    }
  }
  async layerSelectionChange(e) {
    await this._layerSelectionChanged(e);
  }
  async editsComplete(e) {
    const t = e.detail;
    (t === "delete" || t === "add") && (this._allIds = await this.queryAllIds()), await this._refresh();
  }
  async facilityChanged(e) {
    this._updateFloorDefinitionExpression();
  }
  async levelChanged(e) {
    this._floorLevel = e.detail, this._updateFloorDefinitionExpression();
  }
  async siteChanged(e) {
    this._updateFloorDefinitionExpression();
  }
  async noLayersFound() {
    this._layer = void 0, this._allIds = [], this._size = 0, this._clearSelection();
  }
  async clearSelection() {
    await this._validateActiveEdits([], this.selectedIds) && this._clearSelection();
  }
  async mapChanged() {
    this._queryingData = !1, this._creatingFeature = !1, this._clearSelection();
  }
  async featuresSelected(e) {
    e.detail.forEach((i) => {
      const s = this._table?.highlightIds.indexOf(i);
      s && s < 0 && this._table?.highlightIds.add(i);
    });
  }
  createWorkFlowStarted() {
    this._creatingFeature = !0;
  }
  backFromCreateWorkFlow() {
    this._creatingFeature = !1;
  }
  _pasteFeatures() {
    this._layer?.isTable || this._zoom();
  }
  _featuresPasted() {
    this._shouldSelectCreatedFeatures = !0;
  }
  async load() {
    await this._initToolInfos();
  }
  render() {
    const e = this._fetchingData || this._hideTable ? "display-none" : "height-full", t = this._fetchingData ? "" : "display-none", i = this._queryingData ? "" : "display-none", s = this._size.toString(), a = this.selectedIds.length.toString(), l = this.isMobile ? "height-full" : "height-full-adjusted", h = this._canShowFullTextSearch();
    return this._validateActiveActions(), c`<div><calcite-scrim class=${m(i)} .loading=${this._queryingData}></calcite-scrim><calcite-shell><div class=${`width-full ${l}`}><calcite-panel class="height-full width-full panel-header-override">${this._getMapLayerPicker("header-actions-start")}${!this.isMobile && c`${this._getTableControlRow("header-content")}${this._getActionsEnd("header-actions-end")}` || ""}${h && c`<div class="search-container border-bottom"><calcite-input class=search clearable icon=search @calciteInputChange=${(r) => {
      this._searchTextChanged(r);
    }} .placeholder=${this._searchPlaceHolder} title=${this._searchPlaceHolder ?? u} type=search ${b(this._searchNode)}></calcite-input></div>` || ""}<calcite-loader class=${m(t)} .label=${this._translations.fetchingData} scale=l></calcite-loader><div class=${m(e)} ${b(this.onTableNodeCreate)}></div></calcite-panel></div>${this.isMobile ? void 0 : c`<div class="bottom-left text-color height-19" id=solutions-selected-count-div>${(this._translations.recordsTotal?.replace("{{total-number-of-records}}", s) + " | " + this._translations.recordsSelected.replace("{{selected-number-of-records}}", a)).replace("{{total}}", s).replace("{{selected}}", a)}</div>`}</calcite-shell></div>`;
  }
  updated() {
    this._table && this.updateRelatedAttachmentColumns();
  }
  async _searchTextChanged(e) {
    this._fullTextSearchInfo.forEach((t) => {
      t.searchTerm = e.target.value;
    }), this._searchFullText();
  }
  async _searchFullText() {
    let e = [], t = !1;
    if (this._showOnlySelected)
      e = this._tempSelectedIds, t = !0;
    else if (await this._validateActiveEdits([], this.selectedIds))
      this._clearSelection(), this._tempSelectedIds = [];
    else
      return;
    this._searchExpression && this._clearSearchDefinitionExpression();
    let i = [];
    if (this._fullTextSearchInfo?.length && this._fullTextSearchInfo[0].searchTerm) {
      const s = this._layer?.createQuery();
      s.fullText = this._fullTextSearchInfo, i = this._layer ? await this._layer.queryObjectIds(s) : [], t && e?.length && (i = i.filter((a) => e.includes(a))), await this._updateSearchDefinitionExpression(i?.length ? i : [-1]);
    }
    t && i?.length && (this._showOnlySelected = !0, this._table?.highlightIds.addMany(i.reverse())), await new Promise((s) => setTimeout(s, 800)), await this._updateAllIds();
  }
  _clearSearchDefinitionExpression() {
    const e = this._layer?.definitionExpression;
    this._searchExpression && e && e?.indexOf(this._searchExpression) > -1 && this._layer && (e?.indexOf(" AND (" + this._searchExpression) > -1 ? this._layer.definitionExpression = e.replace(` AND (${this._searchExpression})`, "") : this._layer.definitionExpression = e.replace(this._searchExpression, "")), this._searchExpression = "";
  }
  async _updateSearchDefinitionExpression(e) {
    const t = this._layer?.definitionExpression;
    if (this._layer)
      if (e?.length) {
        const i = `objectId in(${e})`;
        this._layer.definitionExpression = this._searchExpression && t && t.includes(this._searchExpression) ? t.replace(this._searchExpression, i) : t ? `${t} AND (${i})` : i, this._searchExpression = i;
      } else
        this._clearSearchDefinitionExpression();
  }
  _canShowFullTextSearch() {
    return this._layer?.capabilities?.query?.supportsFullTextSearch && this._layer.indexes.items.filter((e) => e.indexType == "FullText").length > 0;
  }
  _getFullTextSearchInfo() {
    if (this._fullTextSearchInfo = [], this._layer?.capabilities?.query?.supportsFullTextSearch) {
      const e = this._layer.indexes?.filter((t) => t.indexType == "FullText");
      if (e?.length) {
        const t = [];
        e.forEach((s) => {
          t.push(...s.fields.split(","));
        });
        const i = [];
        t.forEach((s) => {
          const a = this._layer?.getField(s.trim());
          a?.alias && i.push(a.alias);
        }), this._searchPlaceHolder = this._translations.searchPlaceholder.replace("{{field_names}}", i.join(", ")), this._fullTextSearchInfo.push({
          onFields: ["*"],
          searchTerm: "",
          searchType: "prefix"
        });
      }
    }
  }
  _getMapLayerPicker(e) {
    const t = this.isMobile ? "display-none" : "";
    return c`<div class=${`border-end ${t}`} id=solutions-map-layer-picker-container slot=${e ?? u}><map-layer-picker appearance=transparent .configLayerOrderDefined=${this._configLayerOrderDefined} .defaultLayerId=${this.defaultLayerId} display=inline-flex .enabledLayerIds=${this._enabledLayerIds} height=50 .isMobile=${this.isMobile} .mapView=${this.mapView} .showOnlyUpdatableLayers=${this.showOnlyUpdatableLayers} placeholder-icon=layers scale=l .selectedIds=${this._layer ? [this._layer?.id] : []} show-single-layer-as-label show-tables type=dropdown></map-layer-picker></div>`;
  }
  _getLayerOption(e) {
    let t;
    return this.mapInfo?.layerOptions?.layers.some((i) => i.id === e ? (t = i, !0) : !1), t;
  }
  _getActionsEnd(e) {
    const t = this._relatedFeatureTable ? this._relatedFeatureTable.layer : this._layer, i = this._relatedFeatureTable || this._table;
    let s = this._getLayerOption(t?.id || "");
    return c`<div class="display-flex" slot=${e ?? u}><field-selection .configExtraFields=${s?.extraFields} .layer=${t} .mapView=${this.mapView} .table=${i} .tableRef=${this.el}></field-selection>${this.enableShare && !this.isMobile ? this._getShare("share") : void 0}</div>`;
  }
  _getTableControlRow(e) {
    return c`<div class=${"height-51-px width-full display-flex"} slot=${e ?? u} ${b(this._toolbar)}>${this._getActionBar()}</div>`;
  }
  _getActionBar() {
    return c`<calcite-action-bar class=width-full expand-disabled id=${this._getId("bar") ?? u} layout=horizontal><calcite-action-group>${this.isMobile ? void 0 : this._getActions()}</calcite-action-group></calcite-action-bar>`;
  }
  _getActions() {
    return this._toolInfos?.reduce((e, t) => (t && e.push(t.isDanger ? this._getDangerAction(t.icon, t.label, t.func, t.disabled) : this._getAction(t.active, t.icon, t.indicator, t.label, t.func, t.disabled, !!t.loading, t.toolTip)), e), []);
  }
  _validateEnabledActions() {
    const e = this._getIds().length, t = ["zoom-to-object", "pencil", "trash", "erase", "selected-items-filter", "copy"];
    this._toolInfos?.forEach((i) => {
      i && t.indexOf(i.icon) > -1 && (i.disabled = i.icon === "pencil" ? e < 2 || e > g : e < 1, i.toolTip = i.icon === "pencil" ? e > g ? this._translations.featureEditLimitNotice : this._translations.editMultiple : i.toolTip);
    });
  }
  _validateActiveActions() {
    const e = ["filter", "list-check-all", "selected-items-filter"];
    this._toolInfos?.forEach((t) => {
      t && e.indexOf(t.icon) > -1 && (t.icon === "filter" && (t.indicator = this._filterActive), t.icon === "list-check-all" && (t.active = this._selectAllActive), t.icon === "selected-items-filter" && (t.active = this._showOnlySelected, t.label = this._showOnlySelected ? this._translations.showAll : this._translations.showSelected, t.toolTip = this._showOnlySelected ? this._translations.showAll : this._translations.showSelected));
    });
  }
  async _initToolInfos() {
    const e = this._getIds().length > 0, t = this._relatedFeatureTable ? this._relatedFeatureTable.layer.isTable : this._layer?.isTable, i = this.featureSelectionMode === "multiple" && this._layer?.capabilities?.operations.supportsUpdate, s = this._getSelectedIds().length < 2 || this._getSelectedIds().length > g, a = !this.mapHidden && !t, l = !this._relatedFeatureTable && (!this._layer?.isTable || this._hasFilterExpressions()), h = this._featuresEmpty(), r = this.featureSelectionMode === "single";
    let n = this.enableCSV;
    if (this._relatedFeatureTable) {
      const f = await this._queryRelatedFeatures();
      n = f && Object.keys(f).length > 0;
    }
    const d = [];
    l && d.push({
      active: !1,
      icon: "filter",
      indicator: !1,
      label: this._translations.filters,
      func: () => this.toggleFilter.emit(),
      disabled: !1,
      toolTip: this._translations.filters
    }), a && d.push({
      active: !1,
      icon: "zoom-to-object",
      indicator: !1,
      label: this._translations.zoom,
      func: () => {
        this._zoom();
      },
      disabled: !e,
      toolTip: this._translations.zoom
    }), i && d.push({
      active: !1,
      icon: "pencil",
      indicator: !1,
      label: this._translations.editMultiple,
      func: () => this.editMultipleFeatures.emit(this._getSelectedIds()),
      disabled: s,
      toolTip: this._translations.editMultiple
    }), this.showCopyPasteActions && (d.push({
      active: !1,
      icon: "copy",
      indicator: !1,
      label: this._translations.copy,
      func: () => this.copyFeatures.emit({ featuresIds: this._getIds(), layerId: this._layer?.id }),
      disabled: !e,
      toolTip: this._translations.copy
    }), d.push({
      active: !1,
      icon: "paste-with-attribute",
      indicator: !1,
      label: this._translations.paste,
      func: () => this.pasteFeatures.emit(),
      disabled: !this.pasteEnabled,
      toolTip: this._translations.paste
    })), this._deleteEnabled && d.push({
      active: !1,
      icon: "trash",
      indicator: !1,
      label: this._translations.delete,
      func: () => this._showDelete(),
      disabled: !e,
      isDanger: !0,
      toolTip: this._translations.delete
    }), d.push({
      active: !1,
      icon: "erase",
      indicator: !1,
      label: this._translations.clearSelection,
      func: () => {
        this.clearSelection();
      },
      disabled: !e,
      toolTip: this._translations.clearSelection
    }), this._relatedFeatureTable || d.push({
      active: !1,
      icon: "selected-items-filter",
      indicator: !1,
      label: this._showOnlySelected ? this._translations.showAll : this._translations.showSelected,
      func: () => this._toggleShowSelected(),
      disabled: !e,
      toolTip: this._showOnlySelected ? this._translations.showAll : this._translations.showSelected
    }), !r && !this._relatedFeatureTable && d.push({
      active: !1,
      icon: "list-check-all",
      indicator: !1,
      func: async () => await this._selectAll(),
      label: this._translations.selectAll,
      disabled: h,
      toolTip: this._translations.selectAll
    }), !r && !this._relatedFeatureTable && d.push({
      active: !1,
      icon: "compare",
      indicator: !1,
      func: async () => await this._switchSelected(),
      label: this._translations.switchSelected,
      disabled: h,
      toolTip: this._translations.switchSelected
    }), d.push({
      active: !1,
      icon: "refresh",
      indicator: !1,
      func: () => {
        this._refresh();
      },
      label: this._translations.refresh,
      disabled: !1,
      toolTip: this._translations.refresh
    }), n && d.push({
      active: !1,
      icon: "export",
      indicator: !1,
      func: () => {
        this._exportToCSV();
      },
      label: this._translations.exportCSV,
      loading: this._csvExporting,
      disabled: h,
      toolTip: this._translations.exportCSV
    }), this._toolInfos = [...d];
  }
  async _addListenersForLayers() {
    this._layerEditsHandles.forEach((i) => i.remove()), this._layerEditsHandles = [];
    const e = this.mapView, t = [...new Set(this.layerIds)];
    if (!(!e || t.length === 0))
      for (const i of t) {
        const s = await T(e, i);
        if (!s)
          continue;
        const a = s.on("edits", async (l) => {
          const h = Array.isArray(l?.addedFeatures) ? l.addedFeatures : [], r = Array.isArray(l?.updatedFeatures) ? l.updatedFeatures : [];
          if (h.length === 0 && r.length === 0)
            return;
          const n = h.map((_) => _.objectId).filter((_) => _ != null), d = r.map((_) => _.objectId).filter((_) => _ != null);
          if (n.length === 0 && d.length === 0)
            return;
          const f = this._layer?.id;
          if (this._shouldSelectCreatedFeatures) {
            await this._selectFeatures(n, i), i === f && this.featuresAdded.emit(n);
            return;
          } else i === f && n.length > 0 ? (this._searchExpression && (await this._refresh(!1, !0), this._clearSelection(), await this._searchFullText()), await this._refresh(!1, !0), this.initCreateComponent.emit()) : i === f && d.length > 0 && this._searchExpression && (await this._selectFeatures(d, i), await this._refresh());
        });
        a && this._layerEditsHandles.push(a);
      }
  }
  async _selectFeatures(e, t) {
    try {
      const i = this._layer?.id;
      if (t === i) {
        await this._refresh(!1, !0), this._clearSelection(), this._searchExpression && await this._searchFullText();
        const s = [];
        for (const a of e)
          this._allIds.includes(a) && s.push(a);
        s.length > 0 ? this._table?.highlightIds.addMany(s) : await this._refresh();
      } else
        this._clearSelection(), this._pastedFeaturesIds = e, this.requestLayerSelectionChange.emit(t);
      this._shouldSelectCreatedFeatures = !1;
    } catch (i) {
      this._shouldSelectCreatedFeatures = !1, console.error("Failed processing layer edits event", { layerId: t, error: i });
    }
  }
  _updateFloorDefinitionExpression() {
    if (this._floorField && this._floorLevel) {
      const e = `${this._floorField} = '${this._floorLevel}'`, t = this._layer?.definitionExpression;
      this._layer && (this._layer.definitionExpression = t && this._floorExpression && t?.indexOf(this._floorExpression) > -1 ? t.replace(this._floorExpression, e) : t ? `${t} AND (${e})` : e), this._floorExpression = e;
    }
  }
  _featuresEmpty() {
    return this._allIds?.length === 0;
  }
  _hasFilterExpressions() {
    let e = [];
    const t = this._layer?.id;
    return this.mapInfo?.filterConfig?.layerExpressions && t !== void 0 && (e = this.mapInfo.filterConfig.layerExpressions.filter((i) => i.id === t)), e.length > 0;
  }
  _getAction(e, t, i, s, a, l, h, r) {
    const n = this._layer === void 0 ? !0 : l;
    return c`<calcite-action .active=${e} .disabled=${n} .icon=${t} .id=${`layer-table-${t}`} .indicator=${i} .label=${s} .loading=${h} @click=${a} text text-enabled><div class="display-flex"><span class="label-override padding-start-1-4">${s}</span></div></calcite-action>${this._getToolTip("auto", `layer-table-${t}`, r)}`;
  }
  _showDelete() {
    this.showDelete.emit({
      ids: this._getIds()
    });
  }
  _getShare(e) {
    return c`<div id=${this._getId(e) ?? u}><instant-apps-social-share class="height-51 width-51 display-flex" .embed=${this.shareIncludeEmbed} flip-rtl popover-button-icon-scale=s scale=m share-button-color=neutral share-button-type=action .socialMedia=${this.shareIncludeSocial} .view=${this.mapView} ${b(this._shareNode)}></instant-apps-social-share>${this._getToolTip("bottom", e, this._translations.share)}</div>`;
  }
  _updateShareUrl() {
    const e = this._shareNode.value?.shareUrl;
    if (!e)
      return;
    const t = new URL(e);
    this.mapInfo?.id ? t.searchParams.set("webmap", this.mapInfo.id) : t.searchParams.delete("webmap"), this._layer?.id ? t.searchParams.set("layer", this._layer.id) : t.searchParams.delete("layer"), this.selectedIds?.length > 0 ? t.searchParams.set("oid", this.selectedIds.reverse().join(",")) : t.searchParams.delete("oid"), this.appLayout && t.searchParams.set("applayout", this.appLayout), this.selectedRelatedIds?.length > 0 && this._relatedFeatureTable?.layer?.id && (t.searchParams.set("oid", this.selectedRelatedIds.join(",")), t.searchParams.set("layer", this._relatedFeatureTable?.layer?.id.toString())), this._shareNode.value && (this._shareNode.value.autoUpdateShareUrl = !1, this._shareNode.value.shareUrl = t.href);
  }
  _getToolTip(e, t, i) {
    return c`<calcite-tooltip .placement=${e} .referenceElement=${t}><span>${i}</span></calcite-tooltip>`;
  }
  _getId(e) {
    return `solutions-action-${e}`;
  }
  _getDangerAction(e, t, i, s) {
    const a = this._layer === void 0 ? !0 : s;
    return c`<calcite-action class="delete-red" .disabled=${a} .id=${`layer-table-${e}`} .label=${t} @click=${i} text text-enabled><calcite-icon aria-hidden=true class="danger-icon-color" .icon=${e} scale=s></calcite-icon><span class="label-override padding-start-1-4 danger-label-color">${t}</span></calcite-action>${this._getToolTip("bottom", `layer-table-${e}`, t)}`;
  }
  _getIds() {
    let e = this._relatedFeatureTable ?? this._table;
    return this._relatedFeatureTable && this._table && this._table.highlightIds.getItemAt(0) !== this.selectedIds[0] && (e = this._table), e?.highlightIds.map((t) => Number.parseInt(t.toString(), 10)).toArray() ?? [];
  }
  onTableNodeCreate(e) {
    this._tableNode = e;
  }
  async _getTable(e, t) {
    this._layer && (await this._layer.when(() => {
      this._table = new $({
        autoRefreshEnabled: this.enableAutoRefresh,
        autoSaveEnabled: this.enableTableAutosave,
        layer: this._layer,
        view: this.mapView,
        columnReorderingEnabled: this.enableColumnReorder,
        editingEnabled: this._editEnabled && this.enableInlineEdit,
        relatedRecordsEnabled: !0,
        attachmentsEnabled: !0,
        highlightEnabled: !1,
        multiSortEnabled: !1,
        visibleElements: {
          columnDescriptions: !1,
          header: !1,
          menu: !1,
          progress: !1
        },
        tableTemplate: {
          columnTemplates: t
        },
        container: e
      });
    }), await this._table?.when(() => {
      this._table?.viewModel.addHandles(this._table.highlightIds.on("change", (i) => {
        this._handleOnChange(i);
      })), this._table?.viewModel.addHandles(this._table.on("cell-pointerover", this.tempHighlightOnHover.bind(this))), this._table?.viewModel.addHandles(this._table.on("cell-pointerout", this._removeTempHighlight.bind(this))), this._table?.viewModel.addHandles(this._table.on("column-reorder", this._handleColumnReorder.bind(this))), this.listenOn(this._tableNode, "mouseleave", this._removeTempHighlight), this._table?.viewModel.addHandles(p.watch(() => this._table.size, (i) => {
        this._size = i;
      })), p?.watch(
        () => this._table?.relatedTable,
        // eslint-disable-next-line @typescript-eslint/no-misused-promises
        async (i) => {
          if (i) {
            if (i.rowHighlightIds.length) {
              const a = {
                added: [i.rowHighlightIds.getItemAt(0)],
                removed: []
              };
              this._handleOnChange(a);
            }
            const s = i.layer;
            if (this._layerEditHandle = s.on("edits", async () => {
              await new Promise((a) => setTimeout(a, 50)), await this._refresh(!0);
            }), this._checkEditEnabled(s), i.editingEnabled = this._editEnabled && this.enableInlineEdit, i.autoSaveEnabled = this.enableTableAutosave, this._relatedFeatureTable = i, typeof i.layer?.id == "string" && i.layer?.fields) {
              const a = i.layer.popupTemplate?.fieldInfos, l = this._getColumnTemplates(i.layer.id, i.layer.fields, a);
              this._relatedFeatureTable.tableTemplate = new w({
                columnTemplates: l
              });
            }
            i.highlightIds.on("change", (a) => {
              this._handleRelatedRecordsChange(a);
            });
          } else {
            this.selectedRelatedIds = [], this._relatedFeatureTable = void 0, this._layerEditHandle && this._layerEditHandle.remove();
            const s = this._layer;
            this._refresh(), s && this.relatedRecordToggled.emit(s), this._finishOnChange();
          }
          await this._initToolInfos();
        }
      );
    }));
  }
  async _handleRelatedRecordsChange(e) {
    await this._handleOnChange(e), this._updateShareUrl();
  }
  hasAttachmentsEnabled(e) {
    if (!e?.capabilities)
      return !1;
    const { capabilities: { data: { supportsAttachment: t }, operations: { supportsQueryAttachments: i } } } = e;
    return t && i;
  }
  async _handleOnChange(e) {
    if (!await this._validateActiveEdits([...e.added], [...e.removed]))
      return;
    const i = [...this._getIds()];
    let s = this._getSelectedLayer(i);
    this._relatedFeatureTable && this._table?.highlightIds.getItemAt(0) !== this.selectedIds[0] && (s = this._layer, await this._initToolInfos()), s && this.relatedRecordToggled.emit(s), this.featureSelectionMode === "single" && (this._relatedFeatureTable && i.length > 1 ? (this._relatedFeatureTable.highlightIds.remove(i[0]), i.shift()) : i.length > 1 && !this._selectAllActive && (this._table?.highlightIds.remove(i[0]), i.shift())), !this._relatedFeatureTable || this._relatedFeatureTable && this._table?.highlightIds.getItemAt(0) !== this.selectedIds[0] ? (this.selectedRelatedIds = [], this.selectedIds = i.reverse(), this._tempSelectedIds = [...this.selectedIds], this._highlightFeatures(this.selectedIds[0])) : this.selectedRelatedIds = i.reverse(), this._finishOnChange();
  }
  async _validateActiveEdits(e, t) {
    let i = !0;
    if ((this._editor || this._createFeatureEditor) && !this._skipEditCheck) {
      if (this._hasPendingEdits()) {
        this.beforeFeatureSelectionChange.emit();
        let a = !1;
        try {
          this._editor?.activeWorkflow && await this._editor.activeWorkflow.cancel({ force: !1 }), this._createFeatureEditor?.activeWorkflow && await this._createFeatureEditor.activeWorkflow.cancel({ force: !1 });
        } catch (l) {
          a = l?.name === "workflow:cancel-denied";
        }
        if (a) {
          this.continueEditing.emit();
          const l = this._relatedFeatureTable && this._relatedFeatureTable.highlightIds.length > 0 ? this._relatedFeatureTable : this._table;
          i = !1, this._skipEditCheck = !0, e.length > 0 ? l?.highlightIds.removeMany(e) : t.length > 0 && l?.highlightIds.addMany(t);
        }
      }
    } else
      i = !this._skipEditCheck, this._skipEditCheck = !1;
    return this._shouldUpdateTableOnExtentChange = i, i;
  }
  _hasPendingEdits() {
    const e = this._editor?.activeWorkflow?.activeWorkflow?.hasPendingEdits, t = this._createFeatureEditor?.activeWorkflow?.hasPendingEdits;
    return e || t;
  }
  _finishOnChange() {
    this._showOnlySelected && !this._relatedFeatureTable && (this._table && this._getSelectedIds().length > 0 ? this._table.filterBySelectionEnabled = !0 : this._toggleShowSelected());
    const e = this._getSelectedIds();
    setTimeout(() => {
      this.featureSelectionChange.emit(e);
    }, 50);
  }
  _handleColumnReorder() {
    this.columnReorder.emit();
  }
  tempHighlightOnHover(e) {
    if (this._removeTempHighlight(), this._selectedLayerView) {
      const t = e.feature;
      this._temporaryFeatureHandle = this._selectedLayerView?.highlight([t], { name: "temporary" });
    }
  }
  _removeTempHighlight() {
    this._temporaryFeatureHandle && this._temporaryFeatureHandle.remove();
  }
  _highlightFeatures(e) {
    if (this._clearHighlights(), this.selectedIds.length > 0 && this._selectedLayerView && (this._currentFeatureHighlightHandle = this._selectedLayerView?.highlight([e], { name: "current-selection" }), this.selectedIds.length > 1)) {
      const t = this.selectedIds.filter((i) => i !== e);
      this._defaultFeaturesHandle = this._selectedLayerView?.highlight(t, { name: "default" });
    }
  }
  _clearHighlights() {
    this._removeTempHighlight(), this._currentFeatureHighlightHandle && this._currentFeatureHighlightHandle.remove(), this._defaultFeaturesHandle && this._defaultFeaturesHandle.remove();
  }
  _resetColumnTemplates() {
    if (this._layer) {
      const e = this._layer.popupTemplate?.fieldInfos, t = this._getColumnTemplates(this._layer.id, this._layer.fields, e);
      t?.length === 0 ? this._tableNode?.classList.add("display-none") : this._tableNode?.classList.remove("display-none");
      const i = this._table?.tableTemplate?.columnTemplates, s = i && t && i.length !== t.length || t?.some((a, l) => i && i[l] ? JSON.stringify(i[l]) !== JSON.stringify(a) : !1);
      if (this._table && t && (s || !this._columnsInfo)) {
        this._table.tableTemplate = new w({
          columnTemplates: t
        });
        const a = t.map((l) => l.fieldName);
        this._initColumnsInfo(a);
      }
    }
  }
  _setColumnTemplates(e) {
    this._table && e && (this._table.tableTemplate = new w({
      columnTemplates: e
    }));
  }
  async _resetTable() {
    if (this._loaded = !1, this._clearSelection(), this._allIds = await this.queryAllIds(), !this._table && this._layer) {
      const e = this._layer.popupTemplate?.fieldInfos, t = this._getColumnTemplates(this._layer.id, this._layer.fields, e);
      this._tableNode && await this._getTable(this._tableNode, t);
    } else this._table && (this._table.view = this.mapView, this._table.layer = this._layer);
    await this._initLayerRefresh(), this._checkEditEnabled(this._layer), this._table && (this._table.editingEnabled = this._editEnabled && this.enableInlineEdit, this._table.autoSaveEnabled = this.enableTableAutosave, await this._table.when(), setTimeout(() => {
      this._loaded || this.finishLoading();
    }, 1e3), await p.once(() => this._table?.state === "loaded").then(async () => {
      await this.finishLoading();
    }));
  }
  async finishLoading() {
    try {
      this._loaded = !0, this._table?.highlightIds.removeAll(), this._table.objectIds.removeAll(), this._resetColumnTemplates(), this._showOnlySelected = !1, await this._handleDefaults(), await this._sortTable(), await this._initToolInfos(), ["esri-feature-table", "esri-widget"].forEach((t) => {
        this._tableNode && !this._tableNode.classList.contains(t) && this._tableNode.classList.add(t);
      }), this._table && this._pastedFeaturesIds.length > 0 && await this._applyPastedFeatureHighlights();
    } catch (e) {
      console.log(e);
    }
  }
  async _applyPastedFeatureHighlights() {
    const e = [...this._pastedFeaturesIds];
    await new Promise((t) => {
      requestAnimationFrame(() => {
        this._table?.highlightIds.addMany(e), this._pastedFeaturesIds = [], t();
      });
    });
  }
  async _initLayerRefresh() {
    this._refreshHandle && this._refreshHandle.remove(), this._layer && (this._refreshHandle = this._layer.on("refresh", (e) => {
      e.dataChanged && this._updateAllIds();
    }));
  }
  async _updateAllIds() {
    const e = await this.queryAllIds(), t = this.selectedIds.filter((i) => this._allIds.indexOf(i) > -1);
    (JSON.stringify(e) !== JSON.stringify(this._allIds) || JSON.stringify(this.selectedIds) !== JSON.stringify(t)) && (this._allIds = e, this.selectedIds = t, await this._refresh());
  }
  async _handleDefaults() {
    if (!this._defaultOidHonored && this.defaultOid?.length > 0 && this.defaultOid[0] > -1 && this._table && (await this._selectDefaultFeature(this.defaultOid), this._defaultOidHonored = !0, this.defaultOid = [], this._showOnlySelected = !1, this._toggleShowSelected()), !this._defaultGlobalIdHonored && this.defaultGlobalId && this.defaultGlobalId?.length > 0 && this._table && this._layer) {
      const e = await F(this.defaultGlobalId, this._layer), t = e?.length > 0 ? e.map((i) => Number(i.getObjectId())) : void 0;
      t && await this._selectDefaultFeature(t), this._defaultGlobalIdHonored = !0, this.defaultGlobalId = [], this._showOnlySelected = !1, this._toggleShowSelected();
    }
  }
  _initColumnsInfo(e) {
    const t = this._table?.columns.reduce((a, l) => ((!e || e?.indexOf(l.name) > -1) && (a[l.name] = !l.hidden), a), {}), i = this._table?.columns.map((a) => a.name);
    (e && i ? e.filter((a) => i.indexOf(a) < 0) : []).forEach((a) => {
      t[a] = !0;
    }), this._columnsInfo = e ? e.reduce((a, l) => (a[l] = t[l], a), {}) : t;
  }
  async _selectDefaultFeature(e) {
    e.length > 0 && this._table?.highlightIds.addMany(e);
  }
  _checkEditEnabled(e) {
    this._editEnabled = !!(e?.editingEnabled && e?.capabilities?.operations.supportsUpdate), this._deleteEnabled = !!(e?.editingEnabled && e?.capabilities?.operations.supportsDelete);
  }
  async _sortTable() {
    let e = this._layer?.objectIdField, t = "desc", i;
    const s = this.mapInfo?.layerOptions?.layers, a = this._layer?.id;
    s && s.length > 0 && a !== void 0 && (i = s.filter((l) => l.id === a), i && i.length > 0 && (i = i[0], i.sortField && i.fields?.includes(i.sortField) && (e = i.sortField), t = i?.sortOrder ? i.sortOrder : "desc")), this._table && this._layer && (await this._table.when(), await this._layer.when(() => {
      e && this._table?.sortColumn(e, t);
    }));
  }
  async _handleFilterListReset() {
    this._filterActive = !1, this._updateShareUrl(), await this._searchFullText();
  }
  async _handleFilterUpdate(e) {
    if (this._floorExpression && this._layer) {
      const t = this._layer.definitionExpression, i = new RegExp(`${this._floorField} = ['].+[']`, "gm");
      this._layer.definitionExpression = t && this._floorField && t.indexOf(`${this._floorField} = '`) > -1 ? t.replace(i, this._floorExpression) : t ? `${t} AND (${this._floorExpression})` : this._floorExpression;
    }
    this._filterActive = e, this._updateShareUrl(), await this._searchFullText();
  }
  _handleTableOnMapExtent() {
    this._table && (this._filterByExtentHandle = p.when(
      () => this.mapView?.stationary,
      // eslint-disable-next-line @typescript-eslint/no-misused-promises
      async () => {
        if (this._shouldUpdateTableOnExtentChange && this.appLayout === "splitView") {
          if (await new Promise((e) => setTimeout(e, 800)), this._table && this.mapView) {
            this._table.filterGeometry = this.mapView.extent;
            const e = {
              geometry: this.mapView.extent
            }, t = this._layer && await this._layer.queryObjectIds(e), i = this.selectedIds.filter((a) => !t?.includes(a)), s = this._outOFExtentOids.filter((a) => t?.includes(a));
            i.length > 0 && (this._table && this._table?.viewModel?.attachmentsViewOptions?.objectId && this._table.viewModel.hideAttachmentsView(), this._table.highlightIds.removeMany(i), this._outOFExtentOids = [...this._outOFExtentOids, ...i]), s.length > 0 && (this.selectedIds = [.../* @__PURE__ */ new Set([...this.selectedIds, ...s])], this._table.highlightIds.removeAll(), this._table.highlightIds.addMany(this.selectedIds.reverse()), this._outOFExtentOids = this._outOFExtentOids.filter((a) => !s.includes(a)));
          }
          this._allIds = await this.queryAllIds();
        }
      },
      {
        initial: !0
      }
    ));
  }
  async _closeFilter() {
    this._allIds = await this.queryAllIds();
  }
  async queryAllIds() {
    if (this._layer) {
      const e = this._layer.createQuery();
      return e.geometry = this._filterByExtentHandle && this.mapView ? this.mapView.extent : null, e.where = this._layer.definitionExpression || "1=1", await this._layer.queryObjectIds(e);
    } else
      return [];
  }
  async _mapClicked(e) {
    const t = {
      include: this._layer
    }, i = await this.mapView?.hitTest(e.screenPoint, t);
    if (i && i.results.length > 0) {
      const s = i.results;
      if (this.featureSelectionMode === "single") {
        this._table?.highlightIds.removeAll();
        const l = s[0].graphic.getObjectId();
        if (l) {
          const h = this._table?.highlightIds.indexOf(l);
          h !== void 0 && h < 0 && this._table?.highlightIds.add(l);
        }
      } else
        s.forEach((a) => {
          const l = Number(a.graphic.getObjectId()), h = this._table?.highlightIds.indexOf(l);
          h && h < 0 && l && this._table?.highlightIds.add(l);
        });
      this._showOnlySelected && this._table && (this._table.filterBySelectionEnabled = !0);
    }
  }
  async _selectAll() {
    const e = this._allIds, t = e.filter((s) => this.selectedIds.indexOf(s) < 0);
    await this._validateActiveEdits(t, this.selectedIds) && this._table ? (this._table.highlightIds.removeAll(), this._table.highlightIds.addMany(e), this.selectedIds = e, this._finishOnChange(), this._selectAllActive = !0) : this._skipEditCheck = !1;
  }
  _toggleShowSelected() {
    this._showOnlySelected = !this._showOnlySelected, this._table && (this._table.filterBySelectionEnabled = this._showOnlySelected);
  }
  _clearSelection() {
    this._relatedFeatureTable || (this.selectedIds = [], this._outOFExtentOids = [], this._table && this._table?.viewModel?.attachmentsViewOptions?.objectId && this._table.viewModel.hideAttachmentsView(), this._table?.highlightIds.removeAll(), this._clearHighlights(), this._table?.rowHighlightIds.removeAll()), this._relatedFeatureTable && (this._relatedFeatureTable?.highlightIds.removeAll(), this.selectedRelatedIds = []), this._finishOnChange();
  }
  async _switchSelected() {
    const e = [...this.selectedIds], t = this._allIds.reduce((s, a) => (e.indexOf(a) < 0 && s.push(a), s), []).sort((s, a) => s - a);
    await this._validateActiveEdits(t, e) && this._table ? (this._table.highlightIds.removeAll(), this._table.highlightIds.addMany(t), this.selectedIds = t, this._finishOnChange()) : this._skipEditCheck = !1;
  }
  async _exportToCSV() {
    const e = this._relatedFeatureTable ? this._relatedFeatureTable.layer : this._layer;
    if (!e)
      return;
    const t = {};
    let i = this._getIds();
    if (this._relatedFeatureTable?.tableParent && this._relatedFeatureTable.highlightIds.length === 0) {
      const l = this._relatedFeatureTable.tableParent.highlightIds?.getItemAt(0);
      if (l !== void 0) {
        const h = await this._queryRelatedFeatures(), r = [];
        h && h[l]?.features && (h[l].features.forEach((n) => {
          n.attributes && r.push(n.attributes[e.objectIdField]);
        }), i = r.length > 0 ? r : []);
      }
    }
    t[e.id] = {
      selectionSetNames: [e.title || ""],
      ids: i,
      layer: e
    };
    const s = this._relatedFeatureTable ?? this._table;
    if (!s)
      return;
    const a = s && s.columns.toArray().reduce((l, h) => {
      if (!h.hidden) {
        const r = h?.name || h?.fieldName;
        r && l.push(r.toLocaleLowerCase());
      }
      return l;
    }, []);
    this._updateToolInfoLoading("export", !0), this._csvExporting = !0, this.mapView?.map && await x(
      this.mapView.map,
      t,
      !1,
      // formatUsingLayerPopup
      !1,
      // removeDuplicates
      !0,
      // addColumnTitle
      a,
      !0,
      !0
    ), this._updateToolInfoLoading("export", !1), this._csvExporting = !1;
  }
  async _queryRelatedFeatures() {
    const e = this._relatedFeatureTable ? this._relatedFeatureTable ? this._relatedFeatureTable.layer : this._relatedFeatureTable.tableParent?.layer : this._layer, t = this._relatedFeatureTable?.tableParent?.highlightIds?.items[0], i = this._relatedFeatureTable?.tableParent?.layer, s = e?.relationships?.find((h) => i.relationships?.some((r) => r.id === h.id)), a = new D({
      objectIds: [t],
      outFields: ["*"],
      relationshipId: s?.id
    });
    return t && a && await i.queryRelatedFeatures(a).catch(async (h) => {
      console.error(h);
    });
  }
  _updateToolInfoLoading(e, t) {
    this._toolInfos.some((i) => i?.icon === e ? (i.loading = t, !0) : !1);
  }
  async _refresh(e, t) {
    if (t ? !0 : await this._validateActiveEdits([], this.selectedIds)) {
      this._table && await this._table.refresh(), this._relatedFeatureTable && await this._relatedFeatureTable.refresh(), this._allIds = await this.queryAllIds();
      const s = this._getSelectedLayer(this.selectedRelatedIds);
      if (s && this.relatedRecordToggled.emit(s), !e) {
        const a = this._getSelectedIds();
        this.featureSelectionChange.emit(a);
      }
    }
  }
  _getSelectedIds() {
    let e;
    return this._relatedFeatureTable ? this.selectedRelatedIds.length > 0 ? e = this.selectedRelatedIds : e = this._relatedFeatureTable.tableParent?.highlightIds.toArray() ?? [] : e = this.selectedIds, e;
  }
  _getSelectedLayer(e) {
    let t;
    return this._relatedFeatureTable ? e.length > 0 ? t = this._relatedFeatureTable.layer : t = this._relatedFeatureTable.tableParent?.layer : t = this._layer, t;
  }
  async _clearSearchText() {
    if (this._searchNode.value) {
      this._searchNode.value.value = "";
      const e = {
        target: {
          value: ""
        }
      };
      await this._searchTextChanged(e);
    }
  }
  async _zoom() {
    this._layer && this.mapView && await I(this.selectedIds, this._selectedLayerView, this.mapView, !0, void 0, this.zoomToScale);
  }
  async _layerSelectionChanged(e) {
    const t = e.detail[0];
    if (t !== this._layer?.id || this._featuresEmpty()) {
      this._fetchingData = !0, await this._clearSearchText();
      const i = this.mapView && await T(this.mapView, t);
      i && await i.when(async () => {
        this._selectedLayerView = !i.isTable && this.mapView ? await v(this.mapView, i.id) : null, this._table && this._table?.viewModel?.attachmentsViewOptions?.objectId && this._table.viewModel.hideAttachmentsView(), this._shouldUpdateTableOnExtentChange = !0, this._layer = i, await this._initToolInfos(), this._getFullTextSearchInfo();
      });
    }
    this._creatingFeature = !1, this._fetchingData = !1;
  }
  _getColumnTemplates(e, t, i) {
    let s = this._getLayerOption(e);
    const a = this._layer?.attributeTableTemplate?.elements;
    let l = [];
    a?.length > 0 && this.honorMapFieldSettings && (l = a.map((n) => n.fieldName));
    const h = s?.fields && s?.fieldOrder ? s.fieldOrder.filter((n) => s?.fields && s.fields.indexOf(n) > -1) : l.length > 0 ? l : void 0;
    let r;
    return t && (r = t.reduce((n, d) => {
      const f = {
        type: "field",
        fieldName: d.name,
        label: this.getFieldLabel(d, i),
        menuConfig: this._getMenuConfig(d.name)
      };
      return s && s.fields && s?.fields?.length > 0 ? s.fields.indexOf(d.name) > -1 && n.push(f) : l.length > 0 ? l.indexOf(d.name) > -1 && n.push(f) : n.push(f), n;
    }, [])), r ? h ? r?.sort(this._sortFields.bind(this, h)) : r : [];
  }
  updateRelatedAttachmentColumns() {
    let e = this._getLayerOption(this._layer?.id || ""), t = this.hasAttachmentsEnabled(this._layer), i = !0;
    const s = "attachments", a = (e?.extraFields || []).reduce((h, r) => (r.startsWith("related:") ? h.related.push(r.split("related:")[1]) : h.extra.push(r), h), { related: [], extra: [] }), l = a.extra.some((h) => h.toLowerCase() === s);
    a && (t = l && t, i = a.related.length > 0, this._table?.columns.forEach((h) => {
      h.fieldName.startsWith("EsriFeatureTableRelationshipColumn") && (h.hidden = !a.related.some((r) => r.toLowerCase() === (h.effectiveLabel || "").toLowerCase())), h.fieldName.startsWith("EsriFeatureTableAttachmentsColumn") && (h.hidden = !a.extra.some((r) => r.toLowerCase() === h.effectiveLabel.toLowerCase()));
    })), this._table.relatedRecordsEnabled = i, this._table.attachmentsEnabled = t;
  }
  getFieldLabel(e, t) {
    let i = e.alias ? e.alias : e.name;
    return t?.some((s) => s.fieldName === e.name ? (i = s.label, !0) : !1), i || e.name;
  }
  _sortFields(e, t, i) {
    return e?.indexOf(t.fieldName) - e.indexOf(i.fieldName);
  }
  _getMenuConfig(e) {
    return {
      items: [
        {
          label: this._translations.hideField,
          icon: "view-hide",
          autoCloseMenu: !0,
          clickFunction: () => {
            this._handleHideClick(e);
          }
        }
      ]
    };
  }
  _handleHideClick(e) {
    this._columnsInfo && this._table && (this._columnsInfo[e] = !1, this._table.hideColumn(e), this._table.tableTemplate && this._table.tableTemplate.columnTemplates.forEach((t) => {
      t.fieldName === e && (t.visible = !1);
    }));
  }
}
E("layer-table", k);
export {
  k as LayerTable
};
