/* COPYRIGHT Esri - https://js.arcgis.com/1.2/LICENSE.txt */
import { c as customElement } from "../../chunks/runtime.js";
import { e as goToSelection, g as getLayerOrTable, c as getFeatureLayerView } from "../../chunks/mapViewUtils.js";
import { b as queryFeaturesByGlobalID } from "../../chunks/queryUtils.js";
import { d as downloadCSV } from "../../chunks/downloadUtils.js";
import { b as BATCH_EDIT_LIMIT } from "../../chunks/interfaces.js";
import { defineCustomElements } from "@arcgis/instant-apps-components/loader";
import { u as useT9n } from "../../chunks/useT9n.js";
import { css, html, nothing } from "lit";
import { createRef, ref } from "lit-html/directives/ref.js";
import { LitElement, createEvent, noShadowRoot, safeClassMap } from "@arcgis/lumina";
import { b as getEnabledLayerIds } from "../../chunks/helpers.js";
import FeatureTable from "@arcgis/core/widgets/FeatureTable";
import * as reactiveUtils from "@arcgis/core/core/reactiveUtils";
import RelationshipQuery from "@arcgis/core/rest/support/RelationshipQuery";
import TableTemplate from "@arcgis/core/widgets/FeatureTable/support/TableTemplate";
const styles = css`@layer{
/** @license
 * Copyright 2025 Esri
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

: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-background);
}

.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-foreground-1) !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 LayerTable extends LitElement {
  constructor() {
    super();
    this.defaultGlobalId = [];
    this.defaultLayerId = "";
    this.defaultOid = [];
    this.enableAutoRefresh = false;
    this.enableColumnReorder = true;
    this.enableCSV = false;
    this.enableInlineEdit = false;
    this.enableShare = false;
    this.enableTableAutosave = true;
    this.featureSelectionMode = "multiple";
    this.selectedRelatedIds = [];
    this.honorMapFieldSettings = false;
    this.isMobile = false;
    this.mapHidden = false;
    this.showOnlyUpdatableLayers = false;
    this.selectedIds = [];
    this.shareIncludeEmbed = false;
    this.shareIncludeSocial = false;
    this.showNewestFirst = false;
    this.zoomAndScrollToSelected = false;
    this._allIds = [];
    this._configLayerOrderDefined = false;
    this._csvExporting = false;
    this._fetchingData = false;
    this._hideTable = false;
    this._filterActive = false;
    this._selectAllActive = false;
    this._showHideOpen = false;
    this._showOnlySelected = false;
    this._toolInfos = [];
    this._translations = useT9n({ name: "layer-table", blocking: true });
    this._fullTextSearchInfo = [];
    this._searchPlaceHolder = "";
    this._size = 0;
    this._queryingData = false;
    this._editEnabled = false;
    this._enabledLayerIds = [];
    this._defaultGlobalIdHonored = false;
    this._defaultOidHonored = false;
    this._deleteEnabled = false;
    this._floorExpression = "";
    this._floorField = "";
    this._floorLevel = "";
    this._loaded = false;
    this._shareNode = createRef();
    this._toolbar = createRef();
    this._searchExpression = "";
    this._skipEditCheck = false;
    this._tempSelectedIds = [];
    this._outOFExtentOids = [];
    this._shouldUpdateTableOnExtentChange = true;
    this._creatingFeature = false;
    this._searchNode = createRef();
    this.columnReorder = createEvent();
    this.featureSelectionChange = createEvent();
    this.toggleFilter = createEvent();
    this.showDelete = createEvent();
    this.relatedRecordToggled = createEvent();
    this.editMultipleFeatures = createEvent();
    this.listenOn(window, "beforeMapInfoChange", this.beforeMapInfoChange, { capture: true });
    this.listenOn(window, "editorInitialized", this.editorInitialized);
    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);
    defineCustomElements(window);
  }
  static {
    this.properties = { appLayout: 1, defaultGlobalId: [0, {}, { attribute: false }], defaultLayerId: 1, defaultOid: [0, {}, { attribute: false }], enableAutoRefresh: [5, {}, { type: Boolean }], enableColumnReorder: [5, {}, { type: Boolean }], enableCSV: [5, {}, { type: Boolean }], enableInlineEdit: [5, {}, { type: Boolean }], enableShare: [5, {}, { type: Boolean }], enableTableAutosave: [5, {}, { type: Boolean }], featureSelectionMode: 1, selectedRelatedIds: [0, {}, { attribute: false }], honorMapFieldSettings: [5, {}, { type: Boolean }], isMobile: [5, {}, { type: Boolean }], mapHidden: [5, {}, { type: Boolean }], mapInfo: [0, {}, { attribute: false }], mapView: [0, {}, { attribute: false }], showOnlyUpdatableLayers: [5, {}, { type: Boolean }], selectedIds: [0, {}, { attribute: false }], shareIncludeEmbed: [5, {}, { type: Boolean }], shareIncludeSocial: [5, {}, { type: Boolean }], showNewestFirst: [5, {}, { type: Boolean }], zoomAndScrollToSelected: [5, {}, { type: Boolean }], zoomToScale: [9, {}, { type: Number }], _allIds: [16, {}, { state: true }], _configLayerOrderDefined: [16, {}, { state: true }], _csvExporting: [16, {}, { state: true }], _fetchingData: [16, {}, { state: true }], _hideTable: [16, {}, { state: true }], _filterActive: [16, {}, { state: true }], _layer: [16, {}, { state: true }], _selectAllActive: [16, {}, { state: true }], _showHideOpen: [16, {}, { state: true }], _showOnlySelected: [16, {}, { state: true }], _toolInfos: [16, {}, { state: true }], _translations: [16, {}, { state: true }], _fullTextSearchInfo: [16, {}, { state: true }], _searchPlaceHolder: [16, {}, { state: true }], _size: [16, {}, { state: true }], _queryingData: [16, {}, { state: true }] };
  }
  static {
    this.styles = styles;
  }
  static {
    this.shadowRootOptions = noShadowRoot;
  }
  willUpdate(changes) {
    if (changes.has("appLayout")) {
      this.appLayoutWatchHandler();
    }
    if (changes.has("defaultOid")) {
      void this.defaultOidWatchHandler();
    }
    if (changes.has("defaultGlobalId")) {
      void this.defaultGlobalIdWatchHandler();
    }
    if (changes.has("enableCSV")) {
      this.enableCSVWatchHandler();
    }
    if (changes.has("enableInlineEdit")) {
      this.enableInlineEditWatchHandler();
    }
    if (changes.has("mapHidden")) {
      this.mapHiddenWatchHandler();
    }
    if (changes.has("isMobile")) {
      this.isMobileWatchHandler();
    }
    if (changes.has("mapInfo")) {
      void this.mapInfoWatchHandler();
    }
    if (changes.has("mapView")) {
      void this.mapViewWatchHandler();
    }
    if (changes.has("_layer")) {
      void this._layerWatchHandler();
    }
    if (changes.has("selectedIds") && (this.hasUpdated || JSON.stringify(changes.get("selectedIds")) !== JSON.stringify(this.selectedIds))) {
      void this.selectedIdsWatchHandler();
    }
    if (changes.has("selectedRelatedIds") && (this.hasUpdated || JSON.stringify(changes.get("selectedRelatedIds")) !== JSON.stringify(this.selectedRelatedIds))) {
      this.selectedRelatedIdsWatchHandler();
    }
    if (changes.has("_translations")) {
      const newLang = this._translations._lang;
      const oldLang = changes.get("_translations")?._lang;
      if (newLang && oldLang && newLang !== oldLang) {
        this._initToolInfos();
      }
    }
  }
  async appLayoutWatchHandler() {
    await this._initToolInfos();
    this._updateShareUrl();
  }
  async defaultOidWatchHandler() {
    await this._handleDefaults();
  }
  async defaultGlobalIdWatchHandler() {
    await this._handleDefaults();
  }
  async enableCSVWatchHandler() {
    if (this._toolInfos?.length > 0) {
      await this._initToolInfos();
    }
  }
  enableInlineEditWatchHandler() {
    if (this._table) {
      this._table.editingEnabled = this._editEnabled && this.enableInlineEdit;
    }
  }
  async mapHiddenWatchHandler() {
    if (this._toolInfos?.length > 0) {
      await this._initToolInfos();
    }
  }
  async isMobileWatchHandler() {
    if (!this._toolInfos && !this.isMobile) {
      await this._initToolInfos();
    }
  }
  async mapInfoWatchHandler() {
    this._configLayerOrderDefined = "configLayerOrder" in (this.mapInfo?.layerOptions || {});
    this._enabledLayerIds = getEnabledLayerIds(this.mapInfo?.layerOptions?.layers || [], this.mapInfo?.layerOptions?.configLayerOrder);
    if (this._table) {
      this._resetColumnTemplates();
      void this._sortTable();
    }
  }
  async mapViewWatchHandler() {
    if (this._mapClickHandle) {
      this._mapClickHandle.remove();
    }
    if (this.mapView) {
      this._floorExpression = "";
      this._searchExpression = "undefined";
      this.mapView.highlights = [
        {
          name: "default",
          color: "#00FFFF"
        },
        {
          name: "current-selection",
          color: "#ff00ff"
        },
        {
          name: "temporary",
          color: "#FFFF00"
        }
      ];
      this._updateShareUrl();
      this._mapClickHandle = reactiveUtils.on(() => this.mapView, "click", (event) => {
        if (!this._creatingFeature) {
          void this._mapClicked(event);
        }
      });
    }
  }
  async _layerWatchHandler() {
    this._hideTable = false;
    this._fetchingData = true;
    if (!this._layer) {
      this._fetchingData = false;
      this._hideTable = true;
      return;
    }
    try {
      await this._layer.when();
      this._floorField = this._layer.floorInfo?.floorField || "";
      this._updateFloorDefinitionExpression();
      await this._resetTable();
      this._updateShareUrl();
    } catch (err) {
      console.error(err);
      this._hideTable = true;
    } finally {
      this._fetchingData = false;
    }
  }
  async selectedIdsWatchHandler() {
    this._updateShareUrl();
    this._validateEnabledActions();
    if (this._selectAllActive && this.selectedIds.length !== this._allIds.length) {
      this._selectAllActive = false;
    }
    if (this.selectedIds.length > 0) {
      this._table.rowHighlightIds.removeAll();
      this._table.rowHighlightIds.add(this.selectedIds[0]);
    }
    if (this.selectedIds.length === 0) {
      setTimeout(() => {
        this.featureSelectionChange.emit(this.selectedIds);
      }, 700);
    }
  }
  async selectedRelatedIdsWatchHandler() {
    this._validateEnabledActions();
    if (this.selectedRelatedIds.length > 0) {
      this._relatedFeatureTable?.rowHighlightIds.removeAll();
      this._relatedFeatureTable?.rowHighlightIds.add(this.selectedRelatedIds[0]);
    }
  }
  async closeFilter() {
    await this._closeFilter();
  }
  async filterReset() {
    if (this._filterByExtentHandle) {
      if (this._table) {
        this._table.filterGeometry = void 0;
      }
      this._filterByExtentHandle.remove();
      this._filterByExtentHandle = void 0;
    }
    await this._handleFilterListReset();
  }
  async filterUpdate(filterActive, keepTableUpdatingOnMapExtentChange) {
    await this._handleFilterUpdate(filterActive);
    if (keepTableUpdatingOnMapExtentChange) {
      this._shouldUpdateTableOnExtentChange = true;
      this._handleTableOnMapExtent();
    } else if (keepTableUpdatingOnMapExtentChange === false) {
      if (this._table) {
        this._table.filterGeometry = void 0;
      }
      this._filterByExtentHandle?.remove();
      this._filterByExtentHandle = void 0;
      await this._updateAllIds();
    }
  }
  async validateTableUpdate(shouldUpdateTableOnExtentChange) {
    this._shouldUpdateTableOnExtentChange = shouldUpdateTableOnExtentChange;
  }
  async validateActiveEdits() {
    return this._validateActiveEdits([], this.selectedIds);
  }
  async refresh() {
    if (this._table) {
      await this._refresh();
    }
  }
  async setColumnOrder(columnTemplates) {
    this._setColumnTemplates(columnTemplates);
  }
  async beforeMapInfoChange(_evt) {
    const mapPicker = _evt.detail.ref;
    const mapInfo = _evt.detail.mapInfo;
    const hasPendingEdits = this._hasPendingEdits();
    if (hasPendingEdits) {
      _evt.preventDefault();
      const editsDiscarded = await this._validateActiveEdits([], this.selectedIds);
      await mapPicker.setMapByID(editsDiscarded ? mapInfo.id : _evt.detail.currentId, !editsDiscarded);
    }
  }
  async editorInitialized(_evt) {
    this._shouldUpdateTableOnExtentChange = false;
    this._editor = _evt.detail;
  }
  async closeEdit() {
    this._shouldUpdateTableOnExtentChange = true;
    if (this._filterByExtentHandle) {
      this._handleTableOnMapExtent();
    }
  }
  async selectionChanged(_evt) {
    const g = _evt.detail.selectedFeature[0];
    const oid = Number(g.getObjectId());
    const table = this._table;
    if (table.rowHighlightIds.length) {
      table.rowHighlightIds.removeAll();
    }
    table.rowHighlightIds.add(oid);
    this._highlightFeatures(oid);
    if (this.zoomAndScrollToSelected && table && this.mapView) {
      const i = table.viewModel.getObjectIdIndex(oid);
      table.scrollToIndex(i);
      const layer = g.layer;
      const layerViews = this.mapView.allLayerViews.toArray();
      let layerView;
      layerViews.some(async (lv) => {
        if (lv.layer.title === layer?.title && lv.layer.type === "feature") {
          layerView = lv;
          this.mapView && await goToSelection([oid], layerView, this.mapView, true, void 0, this.zoomToScale);
          return true;
        } else {
          return false;
        }
      });
    }
  }
  async beforeLayerSelectionChange(_evt) {
    const hasPendingEdits = this._hasPendingEdits();
    if (hasPendingEdits) {
      _evt.preventDefault();
      const mapLayerPicker = _evt.detail.ref;
      const editsDiscarded = await this._validateActiveEdits([], this.selectedIds);
      return _evt.detail.selectedIds ? await mapLayerPicker.setLayerByIds(editsDiscarded ? _evt.detail.newIds : _evt.detail.currentIds, true) : await mapLayerPicker.setLayerById(editsDiscarded ? _evt.detail.newId : _evt.detail.currentId, true);
    }
  }
  async layerSelectionChange(_evt) {
    await this._layerSelectionChanged(_evt);
  }
  async editsComplete(_evt) {
    const editType = _evt.detail;
    if (editType === "delete" || editType === "add") {
      this._allIds = await this.queryAllIds();
    }
    await this._refresh();
  }
  async facilityChanged(_evt) {
    this._updateFloorDefinitionExpression();
  }
  async levelChanged(_evt) {
    this._floorLevel = _evt.detail;
    this._updateFloorDefinitionExpression();
  }
  async siteChanged(_evt) {
    this._updateFloorDefinitionExpression();
  }
  async noLayersFound() {
    this._layer = void 0;
    this._allIds = [];
    this._size = 0;
    this._clearSelection();
  }
  async clearSelection() {
    const editsDiscarded = await this._validateActiveEdits([], this.selectedIds);
    if (editsDiscarded) {
      this._clearSelection();
    }
  }
  async mapChanged() {
    this._queryingData = false;
    this._creatingFeature = false;
    this._clearSelection();
  }
  async featuresSelected(e) {
    const oids = e.detail;
    oids.forEach((oid) => {
      const index = this._table?.highlightIds.indexOf(oid);
      if (index && index < 0) {
        this._table?.highlightIds.add(oid);
      }
    });
  }
  createWorkFlowStarted() {
    this._creatingFeature = true;
  }
  backFromCreateWorkFlow() {
    this._creatingFeature = false;
  }
  async load() {
    await this._initToolInfos();
  }
  render() {
    const tableNodeClass = this._fetchingData || this._hideTable ? "display-none" : "";
    const loadingClass = this._fetchingData ? "" : "display-none";
    const scrimClass = this._queryingData ? "" : "display-none";
    const total = this._size.toString();
    const selected = this.selectedIds.length.toString();
    const tableHeightClass = this.isMobile ? "height-full" : "height-full-adjusted";
    const showSearch = this._canShowFullTextSearch();
    this._validateActiveActions();
    return html`<div><calcite-scrim class=${safeClassMap(scrimClass)} .loading=${this._queryingData}></calcite-scrim><calcite-shell><div class=${`width-full ${tableHeightClass}`}><calcite-panel class="height-full width-full panel-header-override">${this._getMapLayerPicker("header-actions-start")}${!this.isMobile && html`${this._getTableControlRow("header-content")}${this._getActionsEnd("header-actions-end")}` || ""}${showSearch && html`<div class="search-container border-bottom"><calcite-input class=search clearable icon=search @calciteInputChange=${(_evt) => void this._searchTextChanged(_evt)} .placeholder=${this._searchPlaceHolder} title=${this._searchPlaceHolder ?? nothing} type=search ${ref(this._searchNode)}></calcite-input></div>` || ""}<calcite-loader class=${safeClassMap(loadingClass)} .label=${this._translations.fetchingData} scale=l></calcite-loader><div class=${safeClassMap(tableNodeClass)} ${ref(this.onTableNodeCreate)}></div></calcite-panel></div>${!this.isMobile ? html`<div class="bottom-left text-color height-19" id=solutions-selected-count-div>${(this._translations.recordsTotal?.replace("{{total-number-of-records}}", total) + " | " + this._translations.recordsSelected.replace("{{selected-number-of-records}}", selected)).replace("{{total}}", total).replace("{{selected}}", selected)}</div>` : void 0}</calcite-shell></div>`;
  }
  updated() {
    if (this._table) {
      this.updateRelatedAttachmentColumns();
    }
  }
  async _searchTextChanged(event) {
    this._fullTextSearchInfo.forEach((searchInfo) => {
      searchInfo.searchTerm = event.target.value;
    });
    void this._searchFullText();
  }
  async _searchFullText() {
    let selectedIds = [];
    let showSelected = false;
    if (this._showOnlySelected) {
      selectedIds = this._tempSelectedIds;
      showSelected = true;
    } else {
      const editsDiscarded = await this._validateActiveEdits([], this.selectedIds);
      if (editsDiscarded) {
        this._clearSelection();
        this._tempSelectedIds = [];
      } else {
        return;
      }
    }
    if (this._searchExpression) {
      this._clearSearchDefinitionExpression();
    }
    let searchedIds = [];
    if (this._fullTextSearchInfo?.length && this._fullTextSearchInfo[0].searchTerm) {
      const searchQueryParams = this._layer?.createQuery();
      searchQueryParams.fullText = this._fullTextSearchInfo;
      searchedIds = this._layer ? await this._layer.queryObjectIds(searchQueryParams) : [];
      if (showSelected && selectedIds?.length) {
        searchedIds = searchedIds.filter((id) => selectedIds.includes(id));
      }
      await this._updateSearchDefinitionExpression(searchedIds?.length ? searchedIds : [-1]);
    }
    if (showSelected && searchedIds?.length) {
      this._showOnlySelected = true;
      this._table?.highlightIds.addMany(searchedIds.reverse());
    }
    await new Promise((resolve) => setTimeout(resolve, 800));
    await this._updateAllIds();
  }
  _clearSearchDefinitionExpression() {
    const defExp = this._layer?.definitionExpression;
    if (this._searchExpression && defExp && defExp?.indexOf(this._searchExpression) > -1 && this._layer) {
      if (defExp?.indexOf(" AND (" + this._searchExpression) > -1) {
        this._layer.definitionExpression = defExp.replace(` AND (${this._searchExpression})`, "");
      } else {
        this._layer.definitionExpression = defExp.replace(this._searchExpression, "");
      }
    }
    this._searchExpression = "";
  }
  async _updateSearchDefinitionExpression(searchedIds) {
    const defExp = this._layer?.definitionExpression;
    if (this._layer) {
      if (searchedIds?.length) {
        const searchExp = `objectId in(${searchedIds})`;
        this._layer.definitionExpression = this._searchExpression && defExp && defExp.includes(this._searchExpression) ? defExp.replace(this._searchExpression, searchExp) : defExp ? `${defExp} AND (${searchExp})` : searchExp;
        this._searchExpression = searchExp;
      } else {
        this._clearSearchDefinitionExpression();
      }
    }
  }
  _canShowFullTextSearch() {
    return this._layer?.capabilities?.query?.supportsFullTextSearch && this._layer.indexes.items.filter((i) => i.indexType == "FullText").length > 0;
  }
  _getFullTextSearchInfo() {
    this._fullTextSearchInfo = [];
    if (this._layer?.capabilities?.query?.supportsFullTextSearch) {
      const fullTextIndexes = this._layer.indexes?.filter((i) => i.indexType == "FullText");
      if (fullTextIndexes?.length) {
        const onFields = [];
        fullTextIndexes.forEach((index) => {
          onFields.push(...index.fields.split(","));
        });
        const fieldAlias = [];
        onFields.forEach((fieldName) => {
          const fieldInfo = this._layer?.getField(fieldName.trim());
          if (fieldInfo?.alias) {
            fieldAlias.push(fieldInfo.alias);
          }
        });
        this._searchPlaceHolder = this._translations.searchPlaceholder.replace("{{field_names}}", fieldAlias.join(", "));
        this._fullTextSearchInfo.push({
          onFields: ["*"],
          searchTerm: "",
          searchType: "prefix"
        });
      }
    }
  }
  _getMapLayerPicker(slot) {
    const mobileClass = this.isMobile ? "display-none" : "";
    return html`<div class=${`border-end ${mobileClass}`} id=solutions-map-layer-picker-container slot=${slot ?? nothing}><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(id) {
    let layerOption;
    this.mapInfo?.layerOptions?.layers.some((l) => {
      if (l.id === id) {
        layerOption = l;
        return true;
      }
      return false;
    });
    return layerOption;
  }
  _getActionsEnd(slot) {
    const layerOrTable = this._relatedFeatureTable ? this._relatedFeatureTable.layer : this._layer;
    const table = this._relatedFeatureTable || this._table;
    let layerOption = this._getLayerOption(layerOrTable?.id || "");
    return html`<div class="display-flex" slot=${slot ?? nothing}><field-selection .configExtraFields=${layerOption?.extraFields} .layer=${layerOrTable} .mapView=${this.mapView} .table=${table} .tableRef=${this.el}></field-selection>${this.enableShare && !this.isMobile ? this._getShare("share") : void 0}</div>`;
  }
  _getTableControlRow(slot) {
    return html`<div class=${`height-51-px width-full display-flex`} slot=${slot ?? nothing} ${ref(this._toolbar)}>${this._getActionBar()}</div>`;
  }
  _getActionBar() {
    return html`<calcite-action-bar class=width-full expand-disabled id=${this._getId("bar") ?? nothing} layout=horizontal><calcite-action-group>${!this.isMobile ? this._getActions() : void 0}</calcite-action-group></calcite-action-bar>`;
  }
  _getActions() {
    return this._toolInfos?.reduce((prev, cur) => {
      if (cur) {
        prev.push(cur.isDanger ? this._getDangerAction(cur.icon, cur.label, cur.func, cur.disabled) : this._getAction(cur.active, cur.icon, cur.indicator, cur.label, cur.func, cur.disabled, cur.loading ? true : false, cur.toolTip));
      }
      return prev;
    }, []);
  }
  _validateEnabledActions() {
    const selectedFeaturesIds = this._getIds().length;
    const selectionDependant = ["zoom-to-object", "pencil", "trash", "erase", "selected-items-filter"];
    this._toolInfos?.forEach((ti) => {
      if (ti && selectionDependant.indexOf(ti.icon) > -1) {
        ti.disabled = ti.icon === "pencil" ? selectedFeaturesIds < 2 || selectedFeaturesIds > BATCH_EDIT_LIMIT : selectedFeaturesIds < 1;
        ti.toolTip = ti.icon === "pencil" ? selectedFeaturesIds > BATCH_EDIT_LIMIT ? this._translations.featureEditLimitNotice : this._translations.editMultiple : ti.toolTip;
      }
    });
  }
  _validateActiveActions() {
    const activeDependant = ["filter", "list-check-all", "selected-items-filter"];
    this._toolInfos?.forEach((ti) => {
      if (ti && activeDependant.indexOf(ti.icon) > -1) {
        if (ti.icon === "filter") {
          ti.indicator = this._filterActive;
        }
        if (ti.icon === "list-check-all") {
          ti.active = this._selectAllActive;
        }
        if (ti.icon === "selected-items-filter") {
          ti.active = this._showOnlySelected;
          ti.label = this._showOnlySelected ? this._translations.showAll : this._translations.showSelected;
        }
      }
    });
  }
  async _initToolInfos() {
    const featuresSelected = this._getIds().length > 0;
    const navigatedToRelatedTable = this._relatedFeatureTable ? this._relatedFeatureTable.layer.isTable : this._layer?.isTable;
    const showMultipleEdits = this.featureSelectionMode === "multiple" && this._layer?.capabilities?.operations.supportsUpdate;
    const multipleEditsDisabled = this._getSelectedIds().length < 2 || this._getSelectedIds().length > BATCH_EDIT_LIMIT;
    const showZoom = !this.mapHidden && !navigatedToRelatedTable;
    const showFilterIcon = !this._relatedFeatureTable && (!this._layer?.isTable || this._hasFilterExpressions());
    const featuresEmpty = this._featuresEmpty();
    const singleSelectionMode = this.featureSelectionMode === "single";
    let showExport = this.enableCSV;
    if (this._relatedFeatureTable) {
      const features = await this._queryRelatedFeatures();
      showExport = features && Object.keys(features).length > 0;
    }
    const toolInfos = [];
    if (showFilterIcon) {
      toolInfos.push({
        active: false,
        icon: "filter",
        indicator: false,
        label: this._translations.filters,
        func: () => this.toggleFilter.emit(),
        disabled: false,
        toolTip: this._translations.filters
      });
    }
    if (showZoom) {
      toolInfos.push({
        active: false,
        icon: "zoom-to-object",
        indicator: false,
        label: this._translations.zoom,
        func: () => this._zoom(),
        disabled: !featuresSelected,
        toolTip: this._translations.zoom
      });
    }
    if (showMultipleEdits) {
      toolInfos.push({
        active: false,
        icon: "pencil",
        indicator: false,
        label: this._translations.editMultiple,
        func: () => this.editMultipleFeatures.emit(this._getSelectedIds()),
        disabled: multipleEditsDisabled,
        toolTip: this._translations.editMultiple
      });
    }
    if (this._deleteEnabled) {
      toolInfos.push({
        active: false,
        icon: "trash",
        indicator: false,
        label: this._translations.delete,
        func: () => this._showDelete(),
        disabled: !featuresSelected,
        isDanger: true,
        toolTip: this._translations.delete
      });
    }
    toolInfos.push({
      active: false,
      icon: "erase",
      indicator: false,
      label: this._translations.clearSelection,
      func: () => void this.clearSelection(),
      disabled: !featuresSelected,
      toolTip: this._translations.clearSelection
    });
    if (!this._relatedFeatureTable) {
      toolInfos.push({
        active: false,
        icon: "selected-items-filter",
        indicator: false,
        label: this._showOnlySelected ? this._translations.showAll : this._translations.showSelected,
        func: () => this._toggleShowSelected(),
        disabled: !featuresSelected,
        toolTip: this._showOnlySelected ? this._translations.showAll : this._translations.showSelected
      });
    }
    if (!singleSelectionMode && !this._relatedFeatureTable) {
      toolInfos.push({
        active: false,
        icon: "list-check-all",
        indicator: false,
        func: async () => await this._selectAll(),
        label: this._translations.selectAll,
        disabled: featuresEmpty,
        toolTip: this._translations.selectAll
      });
    }
    if (!singleSelectionMode && !this._relatedFeatureTable) {
      toolInfos.push({
        active: false,
        icon: "compare",
        indicator: false,
        func: async () => await this._switchSelected(),
        label: this._translations.switchSelected,
        disabled: featuresEmpty,
        toolTip: this._translations.switchSelected
      });
    }
    toolInfos.push({
      active: false,
      icon: "refresh",
      indicator: false,
      func: () => void this._refresh(),
      label: this._translations.refresh,
      disabled: false,
      toolTip: this._translations.refresh
    });
    if (showExport) {
      toolInfos.push({
        active: false,
        icon: "export",
        indicator: false,
        func: () => void this._exportToCSV(),
        label: this._translations.exportCSV,
        loading: this._csvExporting,
        disabled: featuresEmpty,
        toolTip: this._translations.exportCSV
      });
    }
    this._toolInfos = [...toolInfos];
  }
  _updateFloorDefinitionExpression() {
    if (this._floorField && this._floorLevel) {
      const floorExp = `${this._floorField} = '${this._floorLevel}'`;
      const defExp = this._layer?.definitionExpression;
      if (this._layer) {
        this._layer.definitionExpression = defExp && this._floorExpression && defExp?.indexOf(this._floorExpression) > -1 ? defExp.replace(this._floorExpression, floorExp) : defExp ? `${defExp} AND (${floorExp})` : floorExp;
      }
      this._floorExpression = floorExp;
    }
  }
  _featuresEmpty() {
    return this._allIds?.length === 0;
  }
  _hasFilterExpressions() {
    let layerExpressions = [];
    const id = this._layer?.id;
    if (this.mapInfo?.filterConfig?.layerExpressions && id !== void 0) {
      layerExpressions = this.mapInfo.filterConfig.layerExpressions.filter((exp) => exp.id === id);
    }
    return layerExpressions.length > 0;
  }
  _getAction(active, icon, indicator, label, func, disabled, loading, toolTip) {
    const _disabled = this._layer === void 0 ? true : disabled;
    return html`<calcite-action .active=${active} appearance=solid .disabled=${_disabled} .icon=${icon} .id=${`layer-table-${icon}`} .indicator=${indicator} .label=${label} .loading=${loading} @click=${func} text text-enabled><div class="display-flex"><span class="label-override padding-start-1-4">${label}</span></div></calcite-action>${this._getToolTip("auto", `layer-table-${icon}`, toolTip)}`;
  }
  _showDelete() {
    this.showDelete.emit({
      ids: this._getIds()
    });
  }
  _getShare(icon) {
    return html`<div id=${this._getId(icon) ?? nothing}><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} ${ref(this._shareNode)}></instant-apps-social-share>${this._getToolTip("bottom", icon, this._translations.share)}</div>`;
  }
  _updateShareUrl() {
    const url = this._shareNode.value?.shareUrl;
    if (!url) {
      return;
    }
    const urlObj = new URL(url);
    if (this.mapInfo?.id) {
      urlObj.searchParams.set("webmap", this.mapInfo.id);
    } else {
      urlObj.searchParams.delete("webmap");
    }
    if (this._layer?.id) {
      urlObj.searchParams.set("layer", this._layer.id);
    } else {
      urlObj.searchParams.delete("layer");
    }
    if (this.selectedIds?.length > 0) {
      urlObj.searchParams.set("oid", this.selectedIds.reverse().join(","));
    } else {
      urlObj.searchParams.delete("oid");
    }
    if (this.appLayout) {
      urlObj.searchParams.set("applayout", this.appLayout);
    }
    if (this.selectedRelatedIds?.length > 0 && this._relatedFeatureTable?.layer?.id) {
      urlObj.searchParams.set("oid", this.selectedRelatedIds.join(","));
      urlObj.searchParams.set("layer", this._relatedFeatureTable?.layer?.id.toString());
    }
    if (this._shareNode.value) {
      this._shareNode.value.autoUpdateShareUrl = false;
      this._shareNode.value.shareUrl = urlObj.href;
    }
  }
  _getToolTip(placement, referenceElement, text) {
    return html`<calcite-tooltip .placement=${placement} .referenceElement=${referenceElement}><span>${text}</span></calcite-tooltip>`;
  }
  _getId(id) {
    return `solutions-action-${id}`;
  }
  _getDangerAction(icon, label, func, disabled) {
    const _disabled = this._layer === void 0 ? true : disabled;
    return html`<div class="display-flex" id=${this._getId(icon) ?? nothing}>${html`<calcite-action appearance=solid .disabled=${_disabled} .id=${`layer-table-${icon}`} @click=${func} text><calcite-icon class="danger-icon-color" .icon=${icon} scale=s></calcite-icon><span class="label-override padding-start-1-4 danger-label-color">${label}</span></calcite-action>`}${this._getToolTip("bottom", `layer-table-${icon}`, label)}</div>`;
  }
  _getIds() {
    let table = this._relatedFeatureTable ?? this._table;
    if (this._relatedFeatureTable && this._table && this._table.highlightIds.getItemAt(0) !== this.selectedIds[0]) {
      table = this._table;
    }
    return table?.highlightIds.map((id) => Number.parseInt(id.toString(), 10)).toArray() ?? [];
  }
  onTableNodeCreate(node) {
    this._tableNode = node;
  }
  async _getTable(node, columnTemplates) {
    if (this._layer) {
      await this._layer.when(() => {
        this._table = new FeatureTable({
          autoRefreshEnabled: this.enableAutoRefresh,
          autoSaveEnabled: this.enableTableAutosave,
          layer: this._layer,
          view: this.mapView,
          columnReorderingEnabled: this.enableColumnReorder,
          editingEnabled: this._editEnabled && this.enableInlineEdit,
          relatedRecordsEnabled: true,
          attachmentsEnabled: true,
          highlightEnabled: false,
          multiSortEnabled: false,
          visibleElements: {
            columnDescriptions: false,
            header: false,
            menu: false,
            progress: false
          },
          tableTemplate: {
            columnTemplates
          },
          container: node
        });
      });
      await this._table?.when(() => {
        this._table?.viewModel.addHandles(this._table.highlightIds.on("change", (_evt) => {
          void this._handleOnChange(_evt);
        }));
        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(reactiveUtils.watch(() => this._table.size, (size) => {
          this._size = size;
        }));
        reactiveUtils?.watch(
          () => this._table?.relatedTable,
          // eslint-disable-next-line @typescript-eslint/no-misused-promises
          async (table) => {
            if (table) {
              if (table.rowHighlightIds.length) {
                const evt = {
                  added: [table.rowHighlightIds.getItemAt(0)],
                  removed: []
                };
                void this._handleOnChange(evt);
              }
              const layer = table.layer;
              this._layerEditHandle = layer.on("edits", async () => {
                await new Promise((resolve) => setTimeout(resolve, 50));
                await this._refresh(true);
              });
              this._checkEditEnabled(layer);
              table.editingEnabled = this._editEnabled && this.enableInlineEdit;
              table.autoSaveEnabled = this.enableTableAutosave;
              this._relatedFeatureTable = table;
              if (typeof table.layer?.id === "string" && table.layer?.fields) {
                const fieldInfos = table.layer.popupTemplate?.fieldInfos;
                const columnTemplates2 = this._getColumnTemplates(table.layer.id, table.layer.fields, fieldInfos);
                this._relatedFeatureTable.tableTemplate = new TableTemplate({
                  columnTemplates: columnTemplates2
                });
              }
              table.highlightIds.on("change", (evt) => {
                void this._handleRelatedRecordsChange(evt);
              });
            } else {
              this.selectedRelatedIds = [];
              this._relatedFeatureTable = void 0;
              if (this._layerEditHandle) {
                this._layerEditHandle.remove();
              }
              const layerOrTable = this._layer;
              void this._refresh();
              if (layerOrTable) {
                this.relatedRecordToggled.emit(layerOrTable);
              }
              this._finishOnChange();
            }
            await this._initToolInfos();
          }
        );
      });
    }
  }
  async _handleRelatedRecordsChange(evt) {
    await this._handleOnChange(evt);
    this._updateShareUrl();
  }
  hasAttachmentsEnabled(layer) {
    if (!layer?.capabilities) {
      return false;
    }
    const { capabilities: { data: { supportsAttachment }, operations: { supportsQueryAttachments } } } = layer;
    return supportsAttachment && supportsQueryAttachments;
  }
  async _handleOnChange(_evt) {
    const handleOnChange = await this._validateActiveEdits([..._evt.added], [..._evt.removed]);
    if (!handleOnChange) {
      return;
    }
    const ids = [...this._getIds()];
    let layerOrTable = this._getSelectedLayer(ids);
    if (this._relatedFeatureTable && this._table?.highlightIds.getItemAt(0) !== this.selectedIds[0]) {
      layerOrTable = this._layer;
      await this._initToolInfos();
    }
    layerOrTable && this.relatedRecordToggled.emit(layerOrTable);
    if (this.featureSelectionMode === "single") {
      if (this._relatedFeatureTable && ids.length > 1) {
        this._relatedFeatureTable.highlightIds.remove(ids[0]);
        ids.shift();
      } else {
        if (ids.length > 1 && !this._selectAllActive) {
          this._table?.highlightIds.remove(ids[0]);
          ids.shift();
        }
      }
    }
    if (!this._relatedFeatureTable || this._relatedFeatureTable && this._table?.highlightIds.getItemAt(0) !== this.selectedIds[0]) {
      this.selectedRelatedIds = [];
      this.selectedIds = ids.reverse();
      this._tempSelectedIds = [...this.selectedIds];
      this._highlightFeatures(this.selectedIds[0]);
    } else {
      this.selectedRelatedIds = ids.reverse();
    }
    this._finishOnChange();
  }
  async _validateActiveEdits(added, removed) {
    let handleOnChange = true;
    if (this._editor && !this._skipEditCheck) {
      const hasPendingEdits = this._hasPendingEdits();
      if (hasPendingEdits) {
        let continueEditing = false;
        try {
          this._editor.viewModel.activeWorkflow && await this._editor.viewModel.activeWorkflow.cancel({
            force: false
          });
        } catch (error) {
          continueEditing = error?.name === "workflow:cancel-denied";
        }
        if (continueEditing) {
          const table = this._relatedFeatureTable && this._relatedFeatureTable.highlightIds.length > 0 ? this._relatedFeatureTable : this._table;
          handleOnChange = false;
          this._skipEditCheck = true;
          if (added.length > 0) {
            table?.highlightIds.removeMany(added);
          } else if (removed.length > 0) {
            table?.highlightIds.addMany(removed);
          }
        }
      }
    } else {
      handleOnChange = !this._skipEditCheck;
      this._skipEditCheck = false;
    }
    this._shouldUpdateTableOnExtentChange = handleOnChange;
    return handleOnChange;
  }
  _hasPendingEdits() {
    const vmHasEdits = this._editor?.viewModel?.hasPendingEdits;
    const awHasEdits = this._editor?.activeWorkflow?.activeWorkflow?.hasPendingEdits;
    return vmHasEdits || awHasEdits;
  }
  _finishOnChange() {
    if (this._showOnlySelected && !this._relatedFeatureTable) {
      if (this._table && this._getSelectedIds().length > 0) {
        this._table.filterBySelectionEnabled = true;
      } else {
        this._toggleShowSelected();
      }
    }
    const selectedIds = this._getSelectedIds();
    setTimeout(() => {
      this.featureSelectionChange.emit(selectedIds);
    }, 50);
  }
  _handleColumnReorder() {
    this.columnReorder.emit();
  }
  tempHighlightOnHover(e) {
    this._removeTempHighlight();
    if (this._selectedLayerView) {
      const temporaryFeature = e.feature;
      this._temporaryFeatureHandle = this._selectedLayerView?.highlight([temporaryFeature], { name: "temporary" });
    }
  }
  _removeTempHighlight() {
    if (this._temporaryFeatureHandle) {
      this._temporaryFeatureHandle.remove();
    }
  }
  _highlightFeatures(currentFeatureId) {
    this._clearHighlights();
    if (this.selectedIds.length > 0 && this._selectedLayerView) {
      this._currentFeatureHighlightHandle = this._selectedLayerView?.highlight([currentFeatureId], { name: "current-selection" });
      if (this.selectedIds.length > 1) {
        const secondaryFeatures = this.selectedIds.filter((id) => id !== currentFeatureId);
        this._defaultFeaturesHandle = this._selectedLayerView?.highlight(secondaryFeatures, { name: "default" });
      }
    }
  }
  _clearHighlights() {
    this._removeTempHighlight();
    if (this._currentFeatureHighlightHandle) {
      this._currentFeatureHighlightHandle.remove();
    }
    if (this._defaultFeaturesHandle) {
      this._defaultFeaturesHandle.remove();
    }
  }
  _resetColumnTemplates() {
    if (this._layer) {
      const fieldInfos = this._layer.popupTemplate?.fieldInfos;
      const columnTemplates = this._getColumnTemplates(this._layer.id, this._layer.fields, fieldInfos);
      if (columnTemplates?.length === 0) {
        this._tableNode?.classList.add("display-none");
      } else {
        this._tableNode?.classList.remove("display-none");
      }
      const tableColumnTemplates = this._table?.tableTemplate?.columnTemplates;
      const hasChange = tableColumnTemplates && columnTemplates && tableColumnTemplates.length !== columnTemplates.length || columnTemplates?.some((ct, i) => {
        if (tableColumnTemplates && tableColumnTemplates[i]) {
          return JSON.stringify(tableColumnTemplates[i]) !== JSON.stringify(ct);
        } else {
          return false;
        }
      });
      if (this._table && columnTemplates && (hasChange || !this._columnsInfo)) {
        this._table.tableTemplate = new TableTemplate({
          columnTemplates
        });
        const fieldNames = columnTemplates.map((f) => f.fieldName);
        this._initColumnsInfo(fieldNames);
      }
    }
  }
  _setColumnTemplates(columnTemplates) {
    if (this._table && columnTemplates) {
      this._table.tableTemplate = new TableTemplate({
        columnTemplates
      });
    }
  }
  async _resetTable() {
    this._loaded = false;
    this._clearSelection();
    this._allIds = await this.queryAllIds();
    if (!this._table && this._layer) {
      const fieldInfos = this._layer.popupTemplate?.fieldInfos;
      const columnTemplates = this._getColumnTemplates(this._layer.id, this._layer.fields, fieldInfos);
      this._tableNode && await this._getTable(this._tableNode, columnTemplates);
    } else if (this._table) {
      this._table.view = this.mapView;
      this._table.layer = this._layer;
    }
    await this._initLayerRefresh();
    this._checkEditEnabled(this._layer);
    if (this._table) {
      this._table.editingEnabled = this._editEnabled && this.enableInlineEdit;
      this._table.autoSaveEnabled = this.enableTableAutosave;
      await this._table.when();
      setTimeout(() => {
        if (!this._loaded) {
          void this.finishLoading();
        }
      }, 1e3);
      await reactiveUtils.once(() => this._table?.state === "loaded").then(async () => {
        await this.finishLoading();
      });
    }
  }
  async finishLoading() {
    try {
      this._loaded = true;
      this._table?.highlightIds.removeAll();
      this._table.objectIds.removeAll();
      this._resetColumnTemplates();
      this._showOnlySelected = false;
      await this._handleDefaults();
      await this._sortTable();
      await this._initToolInfos();
      const tableNodeClasses = ["esri-feature-table", "esri-widget"];
      tableNodeClasses.forEach((c) => {
        if (this._tableNode && !this._tableNode.classList.contains(c)) {
          this._tableNode.classList.add(c);
        }
      });
    } catch (e) {
      console.log(e);
    }
  }
  async _initLayerRefresh() {
    if (this._refreshHandle) {
      this._refreshHandle.remove();
    }
    if (this._layer) {
      this._refreshHandle = this._layer.on("refresh", (_evt) => {
        if (_evt.dataChanged) {
          void this._updateAllIds();
        }
      });
    }
  }
  async _updateAllIds() {
    const allIds = await this.queryAllIds();
    const selectedIds = this.selectedIds.filter((id) => this._allIds.indexOf(id) > -1);
    if (JSON.stringify(allIds) !== JSON.stringify(this._allIds) || JSON.stringify(this.selectedIds) !== JSON.stringify(selectedIds)) {
      this._allIds = allIds;
      this.selectedIds = selectedIds;
      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 = true;
      this.defaultOid = [];
      this._showOnlySelected = false;
      this._toggleShowSelected();
    }
    if (!this._defaultGlobalIdHonored && this.defaultGlobalId && this.defaultGlobalId?.length > 0 && this._table && this._layer) {
      const features = await queryFeaturesByGlobalID(this.defaultGlobalId, this._layer);
      const oids = features?.length > 0 ? features.map((f) => Number(f.getObjectId())) : void 0;
      if (oids) {
        await this._selectDefaultFeature(oids);
      }
      this._defaultGlobalIdHonored = true;
      this.defaultGlobalId = [];
      this._showOnlySelected = false;
      this._toggleShowSelected();
    }
  }
  _initColumnsInfo(fieldNames) {
    const columnsInfo = this._table?.columns.reduce((prev, cur) => {
      if (!fieldNames || fieldNames?.indexOf(cur.name) > -1) {
        prev[cur.name] = !cur.hidden;
      }
      return prev;
    }, {});
    const oldColumnNames = this._table?.columns.map((c) => c.name);
    const newColumnNames = fieldNames && oldColumnNames ? fieldNames.filter((n) => oldColumnNames.indexOf(n) < 0) : [];
    newColumnNames.forEach((c) => {
      columnsInfo[c] = true;
    });
    this._columnsInfo = fieldNames ? fieldNames.reduce((prev, cur) => {
      prev[cur] = columnsInfo[cur];
      return prev;
    }, {}) : columnsInfo;
  }
  async _selectDefaultFeature(oids) {
    if (oids.length > 0) {
      this._table?.highlightIds.addMany(oids);
    }
  }
  _checkEditEnabled(layer) {
    this._editEnabled = layer?.editingEnabled && layer?.capabilities?.operations.supportsUpdate ? true : false;
    this._deleteEnabled = layer?.editingEnabled && layer?.capabilities?.operations.supportsDelete ? true : false;
  }
  async _sortTable() {
    let sortField = this._layer?.objectIdField;
    let sortOrder = "desc";
    let configuredLayer;
    const optionLayers = this.mapInfo?.layerOptions?.layers;
    const id = this._layer?.id;
    if (optionLayers && optionLayers.length > 0 && id !== void 0) {
      configuredLayer = optionLayers.filter((layer) => layer.id === id);
      if (configuredLayer && configuredLayer.length > 0) {
        configuredLayer = configuredLayer[0];
        if (configuredLayer.sortField && configuredLayer.fields?.includes(configuredLayer.sortField)) {
          sortField = configuredLayer.sortField;
        }
        sortOrder = configuredLayer?.sortOrder ? configuredLayer.sortOrder : "desc";
      }
    }
    if (this._table && this._layer) {
      await this._table.when();
      await this._layer.when(() => {
        if (sortField) {
          this._table?.sortColumn(sortField, sortOrder);
        }
      });
    }
  }
  async _handleFilterListReset() {
    this._filterActive = false;
    this._updateShareUrl();
    await this._searchFullText();
  }
  async _handleFilterUpdate(active) {
    if (this._floorExpression && this._layer) {
      const defExp = this._layer.definitionExpression;
      const regEx = new RegExp(`${this._floorField} = ['].+[']`, "gm");
      this._layer.definitionExpression = defExp && this._floorField && defExp.indexOf(`${this._floorField} = '`) > -1 ? defExp.replace(regEx, this._floorExpression) : defExp ? `${defExp} AND (${this._floorExpression})` : this._floorExpression;
    }
    this._filterActive = active;
    this._updateShareUrl();
    await this._searchFullText();
  }
  _handleTableOnMapExtent() {
    if (this._table) {
      this._filterByExtentHandle = reactiveUtils.when(
        () => this.mapView?.stationary,
        // eslint-disable-next-line @typescript-eslint/no-misused-promises
        async () => {
          if (this._shouldUpdateTableOnExtentChange && this.appLayout === "splitView") {
            await new Promise((resolve) => setTimeout(resolve, 800));
            if (this._table && this.mapView) {
              this._table.filterGeometry = this.mapView.extent;
              const query = {
                geometry: this.mapView.extent
              };
              const objectIdsInExtent = this._layer && await this._layer.queryObjectIds(query);
              const outOids = this.selectedIds.filter((id) => !objectIdsInExtent?.includes(id));
              const restoreOids = this._outOFExtentOids.filter((id) => objectIdsInExtent?.includes(id));
              if (outOids.length > 0) {
                if (this._table && this._table?.viewModel?.attachmentsViewOptions?.objectId) {
                  this._table.viewModel.hideAttachmentsView();
                }
                this._table.highlightIds.removeMany(outOids);
                this._outOFExtentOids = [...this._outOFExtentOids, ...outOids];
              }
              if (restoreOids.length > 0) {
                this.selectedIds = [.../* @__PURE__ */ new Set([...this.selectedIds, ...restoreOids])];
                this._table.highlightIds.removeAll();
                this._table.highlightIds.addMany(this.selectedIds.reverse());
                this._outOFExtentOids = this._outOFExtentOids.filter((oid) => !restoreOids.includes(oid));
              }
            }
            this._allIds = await this.queryAllIds();
          }
        },
        {
          initial: true
        }
      );
    }
  }
  async _closeFilter() {
    this._allIds = await this.queryAllIds();
  }
  async queryAllIds() {
    if (this._layer) {
      const query = this._layer.createQuery();
      query.geometry = this._filterByExtentHandle && this.mapView ? this.mapView.extent : null;
      query.where = this._layer.definitionExpression || "1=1";
      return await this._layer.queryObjectIds(query);
    } else {
      return [];
    }
  }
  async _mapClicked(_evt) {
    const opts = {
      include: this._layer
    };
    const hitTestResult = await this.mapView?.hitTest(_evt.screenPoint, opts);
    if (hitTestResult && hitTestResult.results.length > 0) {
      const result = hitTestResult.results;
      if (this.featureSelectionMode === "single") {
        this._table?.highlightIds.removeAll();
        const graphic = result[0].graphic;
        const selectedOID = graphic.getObjectId();
        if (selectedOID) {
          const index = this._table?.highlightIds.indexOf(selectedOID);
          if (index !== void 0 && index < 0) {
            this._table?.highlightIds.add(selectedOID);
          }
        }
      } else {
        result.forEach((result2) => {
          const id = Number(result2.graphic.getObjectId());
          const index = this._table?.highlightIds.indexOf(id);
          if (index && index < 0 && id) {
            this._table?.highlightIds.add(id);
          }
        });
      }
      if (this._showOnlySelected && this._table) {
        this._table.filterBySelectionEnabled = true;
      }
    } else {
      await this.clearSelection();
    }
  }
  async _selectAll() {
    const ids = this._allIds;
    const addedIds = ids.filter((id) => this.selectedIds.indexOf(id) < 0);
    const editsDiscarded = await this._validateActiveEdits(addedIds, this.selectedIds);
    if (editsDiscarded && this._table) {
      this._table.highlightIds.removeAll();
      this._table.highlightIds.addMany(ids);
      this.selectedIds = ids;
      this._finishOnChange();
      this._selectAllActive = true;
    } else {
      this._skipEditCheck = false;
    }
  }
  _toggleShowSelected() {
    this._showOnlySelected = !this._showOnlySelected;
    if (this._table) {
      this._table.filterBySelectionEnabled = this._showOnlySelected;
    }
  }
  _clearSelection() {
    if (!this._relatedFeatureTable) {
      this.selectedIds = [];
      this._outOFExtentOids = [];
      if (this._table && this._table?.viewModel?.attachmentsViewOptions?.objectId) {
        this._table.viewModel.hideAttachmentsView();
      }
      this._table?.highlightIds.removeAll();
      this._clearHighlights();
      this._table?.rowHighlightIds.removeAll();
    }
    if (this._relatedFeatureTable) {
      this._relatedFeatureTable?.highlightIds.removeAll();
      this.selectedRelatedIds = [];
    }
    this._finishOnChange();
  }
  async _switchSelected() {
    const currentIndexes = [...this.selectedIds];
    const ids = this._allIds.reduce((prev, _cur) => {
      if (currentIndexes.indexOf(_cur) < 0) {
        prev.push(_cur);
      }
      return prev;
    }, []).sort((a, b) => a - b);
    const editsDiscarded = await this._validateActiveEdits(ids, currentIndexes);
    if (editsDiscarded && this._table) {
      this._table.highlightIds.removeAll();
      this._table.highlightIds.addMany(ids);
      this.selectedIds = ids;
      this._finishOnChange();
    } else {
      this._skipEditCheck = false;
    }
  }
  async _exportToCSV() {
    const layerOrTable = this._relatedFeatureTable ? this._relatedFeatureTable.layer : this._layer;
    if (!layerOrTable) {
      return;
    }
    const exportInfos = {};
    let ids = this._getIds();
    if (this._relatedFeatureTable?.tableParent && this._relatedFeatureTable.highlightIds.length === 0) {
      const objectId = this._relatedFeatureTable.tableParent.highlightIds?.getItemAt(0);
      if (objectId !== void 0) {
        const result = await this._queryRelatedFeatures();
        const relatedOIDs = [];
        if (result && result[objectId]?.features) {
          result[objectId].features.forEach((feature) => {
            if (feature.attributes) {
              relatedOIDs.push(feature.attributes[layerOrTable.objectIdField]);
            }
          });
          ids = relatedOIDs.length > 0 ? relatedOIDs : [];
        }
      }
    }
    exportInfos[layerOrTable.id] = {
      selectionSetNames: [layerOrTable.title || ""],
      ids,
      layer: layerOrTable
    };
    const table = this._relatedFeatureTable ?? this._table;
    if (!table) {
      return;
    }
    const fields = table && table.columns.toArray().reduce((prev, cur) => {
      if (!cur.hidden) {
        const name = cur?.name || cur?.fieldName;
        if (name) {
          prev.push(name.toLocaleLowerCase());
        }
      }
      return prev;
    }, []);
    this._updateToolInfoLoading("export", true);
    this._csvExporting = true;
    if (this.mapView?.map) {
      await downloadCSV(
        this.mapView.map,
        exportInfos,
        false,
        // formatUsingLayerPopup
        false,
        // removeDuplicates
        true,
        // addColumnTitle
        fields,
        true,
        true
      );
    }
    this._updateToolInfoLoading("export", false);
    this._csvExporting = false;
  }
  async _queryRelatedFeatures() {
    const layerOrTable = !this._relatedFeatureTable ? this._layer : this._relatedFeatureTable ? this._relatedFeatureTable.layer : this._relatedFeatureTable.tableParent?.layer;
    const objectId = this._relatedFeatureTable?.tableParent?.highlightIds?.items[0];
    const parentLayer = this._relatedFeatureTable?.tableParent?.layer;
    const relationship = layerOrTable?.relationships?.find((childReln) => parentLayer.relationships?.some((parentReln) => parentReln.id === childReln.id));
    const relationshipQuery = new RelationshipQuery({
      objectIds: [objectId],
      outFields: ["*"],
      relationshipId: relationship?.id
    });
    const result = objectId && relationshipQuery && await parentLayer.queryRelatedFeatures(relationshipQuery).catch(async (e) => {
      console.error(e);
    });
    return result;
  }
  _updateToolInfoLoading(name, isLoading) {
    this._toolInfos.some((tool) => {
      if (tool?.icon === name) {
        tool.loading = isLoading;
        return true;
      } else {
        return false;
      }
    });
  }
  async _refresh(skipFeatureSelectionChange) {
    const editsDiscarded = await this._validateActiveEdits([], this.selectedIds);
    if (editsDiscarded) {
      if (this._table) {
        await this._table.refresh();
      }
      if (this._relatedFeatureTable) {
        await this._relatedFeatureTable.refresh();
      }
      this._allIds = await this.queryAllIds();
      const layerOrTable = this._getSelectedLayer(this.selectedRelatedIds);
      if (layerOrTable) {
        this.relatedRecordToggled.emit(layerOrTable);
      }
      if (!skipFeatureSelectionChange) {
        const selectedIds = this._getSelectedIds();
        this.featureSelectionChange.emit(selectedIds);
      }
    }
  }
  _getSelectedIds() {
    let ids;
    if (!this._relatedFeatureTable) {
      ids = this.selectedIds;
    } else if (this.selectedRelatedIds.length > 0) {
      ids = this.selectedRelatedIds;
    } else {
      ids = this._relatedFeatureTable.tableParent?.highlightIds.toArray() ?? [];
    }
    return ids;
  }
  _getSelectedLayer(ids) {
    let layerOrTable;
    if (!this._relatedFeatureTable) {
      layerOrTable = this._layer;
    } else if (ids.length > 0) {
      layerOrTable = this._relatedFeatureTable.layer;
    } else {
      layerOrTable = this._relatedFeatureTable.tableParent?.layer;
    }
    return layerOrTable;
  }
  async _clearSearchText() {
    if (this._searchNode.value) {
      this._searchNode.value.value = "";
      const evt = {
        target: {
          value: ""
        }
      };
      await this._searchTextChanged(evt);
    }
  }
  async _zoom() {
    if (this._layer && this.mapView) {
      await goToSelection(this.selectedIds, this._selectedLayerView, this.mapView, true, void 0, this.zoomToScale);
    }
  }
  async _layerSelectionChanged(_evt) {
    const id = _evt.detail[0];
    if (id !== this._layer?.id || this._featuresEmpty()) {
      this._fetchingData = true;
      await this._clearSearchText();
      const layer = this.mapView && await getLayerOrTable(this.mapView, id);
      layer && await layer.when(async () => {
        this._selectedLayerView = !layer.isTable && this.mapView ? await getFeatureLayerView(this.mapView, layer.id) : null;
        if (this._table && this._table?.viewModel?.attachmentsViewOptions?.objectId) {
          this._table.viewModel.hideAttachmentsView();
        }
        this._shouldUpdateTableOnExtentChange = true;
        this._layer = layer;
        await this._initToolInfos();
        this._getFullTextSearchInfo();
      });
    }
    this._creatingFeature = false;
    this._fetchingData = false;
  }
  _getColumnTemplates(id, fields, fieldInfos) {
    let layerOption = this._getLayerOption(id);
    const attributeTableTemplateElements = this._layer?.attributeTableTemplate?.elements;
    let mapFieldOrder = [];
    if (attributeTableTemplateElements?.length > 0 && this.honorMapFieldSettings) {
      mapFieldOrder = attributeTableTemplateElements.map((e) => e.fieldName);
    }
    const fieldOrder = layerOption?.fields && layerOption?.fieldOrder ? layerOption.fieldOrder.filter((f) => layerOption?.fields && layerOption.fields.indexOf(f) > -1) : mapFieldOrder.length > 0 ? mapFieldOrder : void 0;
    let columnTemplates;
    if (fields) {
      columnTemplates = fields.reduce((prev, cur) => {
        const template = {
          type: "field",
          fieldName: cur.name,
          label: this.getFieldLabel(cur, fieldInfos),
          menuConfig: this._getMenuConfig(cur.name)
        };
        if (layerOption && layerOption.fields && layerOption?.fields?.length > 0) {
          if (layerOption.fields.indexOf(cur.name) > -1) {
            prev.push(template);
          }
        } else {
          if (mapFieldOrder.length > 0) {
            if (mapFieldOrder.indexOf(cur.name) > -1) {
              prev.push(template);
            }
          } else {
            prev.push(template);
          }
        }
        return prev;
      }, []);
    }
    if (columnTemplates) {
      return fieldOrder ? columnTemplates?.sort(this._sortFields.bind(this, fieldOrder)) : columnTemplates;
    } else {
      return [];
    }
  }
  updateRelatedAttachmentColumns() {
    let layerOption = this._getLayerOption(this._layer?.id || "");
    let attachmentsEnabled = this.hasAttachmentsEnabled(this._layer);
    let relatedRecordEnabled = true;
    const attachments = "attachments";
    const extraFields = (layerOption?.extraFields || []).reduce((prev, cur) => {
      if (cur.startsWith("related:")) {
        prev.related.push(cur.split("related:")[1]);
      } else {
        prev.extra.push(cur);
      }
      return prev;
    }, { related: [], extra: [] });
    const hasAttachmentsField = extraFields.extra.some((f) => f.toLowerCase() === attachments);
    if (extraFields) {
      attachmentsEnabled = hasAttachmentsField && attachmentsEnabled;
      relatedRecordEnabled = extraFields.related.length > 0;
      this._table?.columns.forEach((col) => {
        if (col.fieldName.startsWith("EsriFeatureTableRelationshipColumn")) {
          col.hidden = extraFields.related.includes(col.effectiveLabel) ? false : true;
        }
        if (col.fieldName.startsWith("EsriFeatureTableAttachmentsColumn")) {
          col.hidden = extraFields.extra.some((f) => f.toLowerCase() === col.effectiveLabel.toLowerCase()) ? false : true;
        }
      });
    }
    this._table.relatedRecordsEnabled = relatedRecordEnabled;
    this._table.attachmentsEnabled = attachmentsEnabled;
  }
  getFieldLabel(field, fieldInfos) {
    let label = field.alias ? field.alias : field.name;
    fieldInfos?.some((fInfo) => {
      if (fInfo.fieldName === field.name) {
        label = fInfo.label;
        return true;
      } else {
        return false;
      }
    });
    return label ? label : field.name;
  }
  _sortFields(sorter, a, b) {
    return sorter?.indexOf(a.fieldName) - sorter.indexOf(b.fieldName);
  }
  _getMenuConfig(name) {
    return {
      items: [
        {
          label: this._translations.hideField,
          icon: "view-hide",
          autoCloseMenu: true,
          clickFunction: () => {
            this._handleHideClick(name);
          }
        }
      ]
    };
  }
  _handleHideClick(name) {
    if (this._columnsInfo && this._table) {
      this._columnsInfo[name] = false;
      this._table.hideColumn(name);
      if (this._table.tableTemplate) {
        this._table.tableTemplate.columnTemplates.forEach((columnTemplate) => {
          if (columnTemplate.fieldName === name) {
            columnTemplate.visible = false;
          }
        });
      }
    }
  }
}
customElement("layer-table", LayerTable);
export {
  LayerTable
};
