/* COPYRIGHT Esri - https://js.arcgis.com/1.2/LICENSE.txt */
import { c as customElement } from "../../chunks/runtime.js";
import { e as goToSelection, h as highlightFeatures, c as getFeatureLayerView } from "../../chunks/mapViewUtils.js";
import { c as queryObjectIds, g as getQueryGeoms, d as queryFeaturesByGeometry } from "../../chunks/queryUtils.js";
import { u as useT9n } from "../../chunks/useT9n.js";
import { css, html } from "lit";
import { createRef, ref } from "lit-html/directives/ref.js";
import { LitElement, createEvent, noShadowRoot, safeClassMap, safeStyleMap } from "@arcgis/lumina";
import { useContextConsumer } from "@arcgis/lumina/context";
import { p as pnContext } from "../../chunks/publicNotificationContext.js";
import esriRequest from "@arcgis/core/request";
import FeatureLayer from "@arcgis/core/layers/FeatureLayer";
import Graphic from "@arcgis/core/Graphic";
import GraphicsLayer from "@arcgis/core/layers/GraphicsLayer";
import Search from "@arcgis/core/widgets/Search";
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;
}

.div-visible {
  display: inherit;
}

.div-not-visible {
  display: none;
}

.padding-bottom-1 {
  padding-bottom: 1rem;
}

.padding-top-1 {
  padding-top: 1rem;
}

.search-widget {
  width: 100% !important;
  border: 1px solid var(--calcite-color-border-input);
}

.w-100 {
  width: 100%;
}

.search-distance {
  display: flex;
  padding-top: 1rem;
}

.font-bold {
  font: bold;
}

.border-bottom {
  border-bottom: 1px solid var(--calcite-color-border-2);
}

.tooltip-container {
  display: flex;
}

.padding-start-1-2 {
  padding-inline-start: 0.5rem;
}

.padding-end-1-2 {
  padding-inline-end: 0.5rem;
}

.icon {
  --calcite-color-icon-color: var(--calcite-color-brand);
}

.tooltip-message {
  padding: 5px 8px;
  font-weight: var(--calcite-font-weight-normal);
  color: var(--calcite-color-text-2);
  max-width: 400px;
}
}`;
class MapSelectTools extends LitElement {
  constructor() {
    super();
    this.bufferColor = [227, 139, 79, 0.8];
    this.bufferOutlineColor = [255, 255, 255];
    this.customLabelEnabled = false;
    this.enabledLayerIds = [];
    this.enableLayerFeatures = true;
    this.enableLayerFeaturesOnLoad = false;
    this.enableSearchDistance = true;
    this.enableSearchDistanceOnLoad = false;
    this.enableSketchTools = true;
    this.geometries = [];
    this.headerLabelClass = "font-bold";
    this.isUpdate = false;
    this.layerViews = [];
    this.noResultText = "";
    this.selectionLayerIds = [];
    this.searchDistanceEnabled = false;
    this.useLayerFeaturesEnabled = false;
    this._numSelected = 0;
    this._searchTerm = "";
    this._selectionLoading = false;
    this._translations = useT9n({ name: "map-select-tools", blocking: true });
    this._bufferTools = createRef();
    this._drawTools = createRef();
    this._labelName = createRef();
    this._pnContextConsumer = useContextConsumer({
      context: pnContext,
      subscribe: true
    });
    this._searchElement = createRef();
    this._selectedIds = [];
    this._selectionLabel = "";
    this._graphics = [];
    this._featuresCollection = {};
    this.selectionSetChange = createEvent();
    this.listenOn(window, "searchConfigurationChange", this.searchConfigurationChangeChanged);
    this.listenOn(window, "distanceChanged", this.distanceChanged);
    this.listenOn(window, "unitChanged", this.unitChanged);
  }
  static {
    this.properties = { bufferColor: 1, bufferOutlineColor: 1, customLabelEnabled: [5, {}, { type: Boolean }], enabledLayerIds: [0, {}, { attribute: false }], enableLayerFeatures: [5, {}, { type: Boolean }], enableLayerFeaturesOnLoad: [5, {}, { type: Boolean }], enableSearchDistance: [5, {}, { type: Boolean }], enableSearchDistanceOnLoad: [5, {}, { type: Boolean }], enableSketchTools: [5, {}, { type: Boolean }], defaultBufferDistance: [9, {}, { type: Number }], defaultBufferUnit: 1, geometries: [0, {}, { attribute: false }], headerLabelClass: 1, isUpdate: [5, {}, { type: Boolean }], layerViews: [0, {}, { attribute: false }], mapView: [0, {}, { attribute: false }], noResultText: 1, searchConfiguration: [0, {}, { attribute: false }], selectionSet: [0, {}, { reflect: false, attribute: false }], selectionLayerIds: [0, {}, { attribute: false }], selectLayerView: [0, {}, { attribute: false }], sketchLineSymbol: [0, {}, { attribute: false }], sketchPointSymbol: [0, {}, { attribute: false }], sketchPolygonSymbol: [0, {}, { attribute: false }], searchDistanceEnabled: [5, {}, { type: Boolean }], useLayerFeaturesEnabled: [5, {}, { type: Boolean }], _numSelected: [16, {}, { state: true }], _searchTerm: [16, {}, { state: true }], _selectionLoading: [16, {}, { state: true }], _translations: [16, {}, { state: true }] };
  }
  static {
    this.styles = styles;
  }
  static {
    this.shadowRootOptions = noShadowRoot;
  }
  willUpdate(changes) {
    if (changes.has("geometries") && (this.hasUpdated || this.geometries?.length > 0)) {
      void this.watchGeometriesHandler(this.geometries, changes.get("geometries"));
    }
    if (changes.has("mapView") && this.mapView) {
      void this.mapViewWatchHandler(this.mapView, changes.get("mapView"));
    }
    if (changes.has("searchConfiguration") && this.searchConfiguration) {
      void this.watchSearchConfigurationHandler(this.searchConfiguration, changes.get("searchConfiguration"));
    }
    if (changes.has("defaultBufferUnit") && this.hasUpdated) {
      if (this.selectionSet) {
        this.selectionSet.unit = this.defaultBufferUnit;
      }
      if (this._bufferTools.value && this.defaultBufferUnit !== void 0) {
        this._bufferTools.value.unit = this.defaultBufferUnit;
      }
      void this._updateLabel();
    }
    if (changes.has("defaultBufferDistance") && this.hasUpdated) {
      if (this.selectionSet) {
        this.selectionSet.distance = this.defaultBufferDistance;
      }
      void this._updateLabel();
    }
  }
  async watchGeometriesHandler(newValue, oldValue) {
    if (newValue !== oldValue) {
      if (newValue.length > 0) {
        return this._highlightWithOIDsOrGeoms();
      }
    }
  }
  async mapViewWatchHandler(v, oldV) {
    if (v && v !== oldV) {
      await this._init();
    }
  }
  async watchSearchConfigurationHandler(newValue, oldValue) {
    if (JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
      await this._initSearchWidget();
    }
  }
  async clearSelection() {
    return this._clearResults(true, true);
  }
  async getSelection() {
    if (!/\S+/gm.test(this._selectionLabel)) {
      await this._updateLabel();
    }
    return {
      id: this.isUpdate && this.selectionSet ? this.selectionSet.id : Date.now(),
      searchResult: this._searchResult,
      buffer: this._bufferGeometry,
      distance: this._bufferTools.value?.distance,
      download: true,
      unit: this._bufferTools.value?.unit,
      label: this._selectionLabel,
      selectedIds: this._selectedIds,
      layerView: this.selectLayerView,
      geometries: this.geometries,
      graphics: this._graphics,
      selectLayers: this.layerViews,
      skipGeomOIDs: this._skipGeomOIDs,
      searchDistanceEnabled: this.searchDistanceEnabled,
      workflowType: this._workflowType,
      useLayerFeaturesEnabled: this.useLayerFeaturesEnabled,
      sketchGraphic: this._sketchGraphic
    };
  }
  searchConfigurationChangeChanged(event) {
    this.searchConfiguration = event.detail;
  }
  async distanceChanged(event) {
    await this._distanceChanged(event.detail);
  }
  async unitChanged(event) {
    if (event.detail.newValue !== event.detail.oldValue) {
      this._unit = event.detail.newValue;
      await this._updateLabel();
    }
  }
  async loaded() {
    await this._init();
  }
  render() {
    const mapToolsClass = this.enableSketchTools ? "" : "display-none";
    const mapToolsContainerClass = this.enableSketchTools ? "padding-top-1" : "";
    return html`${this._getMapLayerPicker()}<div class="border-bottom"></div><div class="padding-top-sides-1"><div class="search-widget" ${ref(this._searchElement)}></div><div class=${safeClassMap(mapToolsContainerClass)}><map-draw-tools active class=${safeClassMap(mapToolsClass)} .editGraphicsEnabled=${!this.useLayerFeaturesEnabled} .graphics=${this._graphics} .mapView=${this.mapView} @sketchGraphicsChange=${(_evt) => void this._sketchGraphicsChanged(_evt)} .pointSymbol=${this.sketchPointSymbol} .polygonSymbol=${this.sketchPolygonSymbol} .polylineSymbol=${this.sketchLineSymbol} ${ref(this._drawTools)}></map-draw-tools></div>${this.enableSearchDistance ? this._getBufferOptions() : void 0}${this.enableLayerFeatures ? this._getUseLayerFeaturesOptions() : void 0}${this._getNumSelected()}</div><div class="border-bottom"></div>${this._getNameInput()}`;
  }
  _getBufferOptions() {
    if (this.enableSearchDistanceOnLoad) {
      this.searchDistanceEnabled = true;
      this.enableSearchDistanceOnLoad = false;
    }
    const showBufferToolsClass = this.searchDistanceEnabled ? "search-distance" : "div-not-visible";
    const bufferDistance = typeof this.selectionSet?.distance === "number" ? this.selectionSet.distance : this.defaultBufferDistance;
    return html`<div><div class="padding-top-1 display-flex"><calcite-label class="label-margin-0 w-100" layout=inline-space-between><div class="tooltip-container">${this._translations.searchDistance}<calcite-icon class="padding-start-1-2 icon" .flipRtl=${!(this._translations._lang?.toLowerCase() === "he")} icon=question id=search-distance-icon scale=s></calcite-icon></div></calcite-label><calcite-popover closable label overlay-positioning=fixed reference-element=search-distance-icon><span class="tooltip-message">${this._translations.useSearchDistanceTootip}</span></calcite-popover><calcite-switch .checked=${this.searchDistanceEnabled} @calciteSwitchChange=${() => this.searchDistanceEnabled = !this.searchDistanceEnabled}></calcite-switch></div><div class=${safeClassMap(showBufferToolsClass)}><buffer-tools .disabled=${!this.searchDistanceEnabled} .distance=${bufferDistance} .geometries=${this.geometries} @bufferComplete=${(_evt) => void this._bufferComplete(_evt)} .unit=${this.selectionSet?.unit || this.defaultBufferUnit} ${ref(this._bufferTools)}></buffer-tools></div></div>`;
  }
  _getUseLayerFeaturesOptions() {
    if (this.enableLayerFeaturesOnLoad) {
      this.useLayerFeaturesEnabled = true;
      this.enableLayerFeaturesOnLoad = false;
    }
    const useLayerFeaturesClass = this.useLayerFeaturesEnabled ? "div-visible" : "div-not-visible";
    return html`<div><div class="padding-top-1 display-flex"><calcite-label class="label-margin-0 w-100" layout=inline-space-between><div class="tooltip-container">${this._translations.useLayerFeatures}<calcite-icon class="padding-start-1-2 icon" .flipRtl=${!(this._translations._lang?.toLowerCase() === "he")} icon=question id=use-layer-features-icon scale=s></calcite-icon></div></calcite-label><calcite-popover closable label overlay-positioning=fixed reference-element=use-layer-features-icon><span class="tooltip-message">${this._translations.useLayerFeaturesTooltip}</span></calcite-popover><calcite-switch .checked=${this.useLayerFeaturesEnabled} @calciteSwitchChange=${() => {
      this._useLayerFeaturesEnabledChanged();
    }}></calcite-switch></div><div class=${`${useLayerFeaturesClass} padding-top-1`}><map-layer-picker .enabledLayerIds=${this.selectionLayerIds} .mapView=${this.mapView} @layerSelectionChange=${(_evt) => {
      void this._layerSelectionChange(_evt);
    }} .selectedIds=${this.layerViews.map((l) => l.layer.id)}></map-layer-picker></div></div>`;
  }
  _getNumSelected() {
    const selectionLoading = this._translations._lang === "en" ? `${this._translations.selectionLoading}...` : this._translations.selectionLoading;
    return html`<div class="padding-top-1 padding-bottom-1" style=${safeStyleMap({ "align-items": "end", "display": "flex" })}>${this._selectionLoading ? html`<div><calcite-loader class="info-blue padding-end-1-2" inline .label=${selectionLoading || ""} scale=m type=indeterminate></calcite-loader></div>` : html`<calcite-icon class="info-blue padding-end-1-2" icon=feature-layer scale=s></calcite-icon>`}<calcite-input-message class="info-blue" scale=m>${this._selectionLoading ? selectionLoading : this.noResultText && this._numSelected === 0 ? this.noResultText : this._translations.selectedFeatures.replace("{{n}}", this._numSelected.toString())}</calcite-input-message></div>`;
  }
  _getNameInput() {
    const nameLabelClass = this.customLabelEnabled ? "" : "display-none";
    return html`<div class=${`padding-sides-1 padding-top-1 ${nameLabelClass}`}><calcite-label class=${safeClassMap(this.headerLabelClass)}>${this._translations.listName}<calcite-input @input=${() => {
      this._selectionLabel = this._labelName.value ? this._labelName.value.value : "";
    }} .placeholder=${this._translations.listNamePlaceholder} .value=${this._selectionLabel || ""} ${ref(this._labelName)}></calcite-input></calcite-label></div>`;
  }
  _getMapLayerPicker() {
    const id = this.selectionSet?.layerView?.layer.id;
    return html`<div class="display-flex padding-sides-1 padding-bottom-1"><calcite-label class=${`${this.headerLabelClass} width-full label-margin-0`}>${this._translations.inputLayer}<map-layer-picker .enabledLayerIds=${this.enabledLayerIds} .mapView=${this.mapView} @layerSelectionChange=${(_evt) => void this._inputLayerSelectionChange(_evt)} .selectedIds=${this.selectLayerView ? [this.selectLayerView.layer.id] : this.selectionSet && id !== void 0 ? [id] : []}></map-layer-picker></calcite-label></div>`;
  }
  async _init() {
    this._initGraphicsLayer();
    await this._initSelectionSet();
    await this._initSearchWidget();
  }
  async _initSelectionSet() {
    if (this.selectionSet) {
      this._searchTerm = this.selectionSet.searchResult?.name;
      this._searchResult = this.selectionSet.searchResult;
      this._selectedIds = this.selectionSet.selectedIds;
      this._skipGeomOIDs = this.selectionSet.skipGeomOIDs || [];
      this.searchDistanceEnabled = this.selectionSet.searchDistanceEnabled;
      this.useLayerFeaturesEnabled = this.selectionSet.useLayerFeaturesEnabled;
      this._distance = this.selectionSet.searchDistanceEnabled ? this.selectionSet.distance : 0;
      this._unit = this.selectionSet.unit;
      this._workflowType = this.selectionSet.workflowType;
      this.selectLayerView = this.selectionSet.layerView;
      this._sketchGraphic = this.selectionSet.sketchGraphic;
      this.geometries = [...this.selectionSet?.geometries || []];
      this._graphics = this.geometries.reduce((prev, cur) => {
        const symbol = cur.type === "point" ? this.sketchPointSymbol : cur.type === "polyline" ? this.sketchLineSymbol : this.sketchPolygonSymbol;
        prev.push(new Graphic({
          geometry: cur,
          symbol
        }));
        return prev;
      }, []);
      this._selectionLabel = this.selectionSet?.label;
      if (!this.useLayerFeaturesEnabled) {
        await this._drawTools.value?.updateGraphics();
      }
      this.selectionSet.layerView && this.mapView && await goToSelection(this.selectionSet.selectedIds, this.selectionSet.layerView, this.mapView, false);
    }
  }
  async _initSearchWidget() {
    if (this.mapView && this._searchElement.value) {
      const searchConfiguration = this.searchConfiguration && this._getSearchConfig(this.searchConfiguration, this.mapView);
      const searchOptions = {
        view: this.mapView,
        container: this._searchElement.value,
        searchTerm: this._searchTerm,
        ...searchConfiguration
      };
      if (!this._searchWidget) {
        this._searchWidget = new Search(searchOptions);
      } else {
        this._searchWidget.view = this.mapView;
        this._searchWidget.searchTerm = this._searchTerm;
      }
      if (this._searchWidget) {
        this._searchWidget.popupEnabled = false;
        this._searchWidget.resultGraphicEnabled = false;
        this._searchWidget.viewModel.addHandles(this._searchWidget.on("search-clear", () => {
          const clearLabel = this._searchClearLabel();
          if (this._searchResult?.name) {
            void this._clearResults(false, clearLabel);
          }
        }));
        this._searchWidget.viewModel.addHandles(this._searchWidget.on("select-result", (searchResults) => {
          void this._selectResult(searchResults.result);
        }));
        await this._searchWidget.when(() => {
          if (this._searchWidget) {
            this._searchWidget.allPlaceholder = this.searchConfiguration?.allPlaceholder && this.searchConfiguration.allPlaceholder.toLowerCase() !== "find address or place" ? this.searchConfiguration.allPlaceholder : this._translations.placeholder;
          }
        });
      }
    }
  }
  async _selectResult(result) {
    if (result) {
      this._searchResult = result;
      const resultFeature = result.feature;
      const resultLayer = resultFeature?.layer;
      const selectLayer = this.selectLayerView?.layer;
      const oid = Number(resultFeature?.getObjectId());
      let resultLayerSourceUrl;
      if (resultLayer?.sourceJSON?.isView && resultLayer.url) {
        resultLayerSourceUrl = await this._getViewSourceUrl(resultLayer.url);
      }
      let selectLayerSourceUrl;
      if (selectLayer?.sourceJSON?.isView && selectLayer.url) {
        selectLayerSourceUrl = await this._getViewSourceUrl(selectLayer.url);
      }
      const rUrl = resultLayer?.url?.toLowerCase();
      const rSourceUrl = resultLayerSourceUrl?.toLowerCase();
      const sUrl = selectLayer?.url?.toLowerCase();
      const sSourceUrl = selectLayerSourceUrl?.toLowerCase();
      const useOIDs = rUrl && sUrl && (rUrl === sUrl || rUrl === sSourceUrl || rSourceUrl === sUrl || rSourceUrl === sSourceUrl) && !Number.isNaN(oid);
      const oids = useOIDs ? [oid] : void 0;
      this._workflowType = "SEARCH";
      void this._updateLabel();
      const graphics = [result.feature];
      this._updateSelection(graphics, useOIDs, oids);
      if (this._drawTools.value) {
        this._drawTools.value.graphics = graphics;
      }
      if (this._searchWidget?.resultGraphic) {
        this._searchWidget.resultGraphic.visible = false;
      }
    } else {
      const clearLabel = this._searchClearLabel();
      void this._clearResults(false, clearLabel);
    }
  }
  async _getViewSourceUrl(url) {
    let sourceUrl = "";
    const resultLayerSourcesUrl = `${url}/sources?f=json`;
    try {
      const _request = await esriRequest(resultLayerSourcesUrl, {
        query: {
          f: "json"
        }
      });
      if (_request?.data?.services?.length === 1) {
        sourceUrl = _request.data.services[0].url;
      }
    } catch (error) {
      console.log(error);
    }
    return sourceUrl;
  }
  _searchClearLabel() {
    return this._searchResult?.name && this._labelName.value && this._labelName.value.value.indexOf(this._searchResult.name) > -1;
  }
  _getSearchConfig(searchConfiguration, view) {
    const sources = searchConfiguration?.sources;
    if (sources && sources?.length > 0) {
      searchConfiguration = {
        ...searchConfiguration,
        includeDefaultSources: false
      };
      sources.forEach((source) => {
        const isLayerSource = source.hasOwnProperty("layer");
        if (isLayerSource) {
          const layerSource = source;
          const layerId = layerSource.layer?.id;
          const layerFromMap = layerId ? view.map?.findLayerById(layerId) : null;
          const layerUrl = layerSource?.layer?.url;
          if (layerFromMap && layerSource) {
            layerSource.layer = layerFromMap;
          } else if (layerUrl) {
            layerSource.layer = new FeatureLayer(layerUrl);
          }
        }
      });
      sources?.forEach((source) => {
        const isLocatorSource = source.hasOwnProperty("locator");
        if (isLocatorSource) {
          const locatorSource = source;
          if (locatorSource?.name === "ArcGIS World Geocoding Service") {
            const outFields = locatorSource.outFields || ["Addr_type", "Match_addr", "StAddr", "City"];
            locatorSource.outFields = outFields;
            locatorSource.singleLineFieldName = "SingleLine";
          }
          locatorSource.url = locatorSource.url;
          delete locatorSource.url;
        }
      });
    } else {
      searchConfiguration = {
        ...searchConfiguration,
        includeDefaultSources: true
      };
    }
    return searchConfiguration;
  }
  _initGraphicsLayer() {
    const _state = this._pnContextConsumer.value;
    const title = this._translations.bufferLayer;
    if (this.mapView) {
      const bufferIndex = this.mapView.map.layers.findIndex((l) => l.title === title);
      if (bufferIndex > -1) {
        this._bufferGraphicsLayer = this.mapView.map.layers.getItemAt(bufferIndex);
      } else {
        this._bufferGraphicsLayer = new GraphicsLayer({ title, listMode: "hide" });
        if (this._bufferGraphicsLayer) {
          _state.managedLayers[title] = "buffer";
          const sketchIndex = this.mapView.map.layers.findIndex((l) => l.title === this._translations.sketchLayer);
          if (sketchIndex > -1) {
            this.mapView.map.layers.add(this._bufferGraphicsLayer, sketchIndex);
          } else {
            this.mapView.map.layers.add(this._bufferGraphicsLayer);
          }
        }
      }
    }
  }
  async _sketchGraphicsChanged(event, forceUpdate = false) {
    const graphics = event.detail.graphics;
    if (graphics.length > 0 && graphics[0]) {
      if (!forceUpdate) {
        this._sketchGraphic = graphics[0];
      }
      this._workflowType = this.useLayerFeaturesEnabled ? "SELECT" : "SKETCH";
      if (this._workflowType === "SKETCH") {
        this._drawTools.value && await this._drawTools.value.updateGraphics();
      }
      await this._updateLabel();
      this._clearSearchWidget();
      if (this.useLayerFeaturesEnabled && !forceUpdate) {
        const geometries = Array.isArray(graphics) ? graphics.map((g) => g.geometry) : this.geometries;
        await this._selectLayerFeatures(geometries[0]);
      } else {
        const oids = graphics.reduce((prev, cur) => {
          if (cur?.layer?.objectIdField) {
            prev.push(Number(cur.attributes[cur.layer.objectIdField]));
          } else if (cur.getObjectId) {
            prev.push(Number(cur.getObjectId()));
          }
          return prev;
        }, []);
        const useOIDs = event.detail.useOIDs && oids.length > 0;
        this._updateSelection(graphics, useOIDs, oids);
        if (useOIDs) {
          await this._highlightFeatures(oids);
        }
      }
    } else {
      await this._clearResults(true, true);
    }
  }
  async _highlightWithOIDsOrGeoms() {
    if (this._skipGeomOIDs && this._skipGeomOIDs?.length > 0) {
      this._selectedIds = this._skipGeomOIDs;
      return this._highlightFeatures(this._selectedIds);
    } else {
      return this._geomQuery(this.geometries);
    }
  }
  async _highlightFeatures(ids) {
    const _state = this._pnContextConsumer.value;
    _state.removeHandles();
    if (ids.length > 0) {
      if (this.selectLayerView && this.mapView) {
        const handle = await highlightFeatures(ids, this.selectLayerView, this.mapView);
        _state.highlightHandles.push(handle);
      }
    }
    this._numSelected = ids.length;
    this.selectionSetChange.emit(ids.length);
  }
  async _selectFeatures(geometries) {
    this._selectionLoading = true;
    this._selectedIds = this.selectLayerView && await queryObjectIds(geometries, this.selectLayerView.layer) || [];
    this._selectionLoading = false;
    if (this._drawTools.value) {
      this._drawTools.value.graphics = this._graphics;
    }
    await this._highlightFeatures(this._selectedIds);
  }
  async _bufferComplete(_evt) {
    this._bufferGeometry = Array.isArray(_evt.detail) ? _evt.detail[0] : _evt.detail;
    let oldValue = this._bufferTools.value && Number(this._bufferTools.value.distance);
    let newValue = 0;
    if (this._bufferGeometry) {
      const symbol = {
        type: "simple-fill",
        color: this.bufferColor,
        outline: {
          color: this.bufferOutlineColor,
          width: 1
        }
      };
      const polygonGraphic = new Graphic({
        geometry: this._bufferGeometry,
        symbol
      });
      if (this._bufferGraphicsLayer && polygonGraphic && this.mapView) {
        this._bufferGraphicsLayer.removeAll();
        this._bufferGraphicsLayer.add(polygonGraphic);
        await this._selectFeatures([this._bufferGeometry]);
        if (polygonGraphic.geometry?.extent) {
          await this.mapView.goTo(polygonGraphic.geometry.extent);
        }
      }
      newValue = oldValue;
      oldValue = 0;
    } else {
      if (this._bufferGraphicsLayer) {
        this._bufferGraphicsLayer.removeAll();
      }
      await this._highlightWithOIDsOrGeoms();
    }
    await this._distanceChanged({
      oldValue,
      newValue
    });
  }
  _geomQuery(geometries) {
    const queryGeoms = getQueryGeoms(geometries);
    if (queryGeoms) {
      return this._selectFeatures(queryGeoms);
    } else {
      return Promise.resolve();
    }
  }
  async _clearResults(clearSearchWidget = true, clearLabel = false) {
    this._selectedIds = [];
    this._distance = void 0;
    this._unit = void 0;
    if (clearLabel) {
      this._selectionLabel = "";
      if (this._labelName.value) {
        this._labelName.value.value = "";
      }
    }
    if (this._bufferGraphicsLayer) {
      this._bufferGraphicsLayer.removeAll();
    }
    if (clearSearchWidget && this._searchWidget) {
      this._clearSearchWidget();
    }
    this._pnContextConsumer.value.removeHandles();
    if (this._drawTools.value?.clear) {
      this._graphics = [];
      await this._drawTools.value.clear();
    }
    this._numSelected = this._selectedIds.length;
    this.selectionSetChange.emit(this._numSelected);
  }
  _clearSearchWidget() {
    this._searchWidget?.clear();
    this._searchResult = void 0;
  }
  _updateSelection(graphics, useOIDs, oids) {
    this._selectedIds = useOIDs && oids ? oids : this._selectedIds;
    this._skipGeomOIDs = useOIDs ? oids : void 0;
    this.geometries = Array.isArray(graphics) ? graphics.reduce((prev, cur) => {
      if (cur.geometry) {
        prev.push(cur.geometry);
      }
      return prev;
    }, []) : this.geometries;
    this._graphics = graphics;
  }
  async _updateLabel() {
    if (this.enableSearchDistance) {
      const hasSketch = this._translations.sketch && this._selectionLabel.indexOf(this._translations.sketch) > -1;
      const hasSelect = this._translations.select && this._selectionLabel.indexOf(this._translations.select) > -1;
      const hasSearch = this._selectionLabel.indexOf(this._searchResult?.name) > -1;
      const label = this._workflowType === "SEARCH" ? this._searchResult?.name : this._workflowType === "SELECT" ? this._translations.select : this._translations.sketch;
      const _unit = this._bufferTools.value ? this._bufferTools.value.unit : this._unit;
      const unit = this._bufferTools.value && _unit && await this._bufferTools.value.getTranslatedUnit(_unit);
      const distance = Number.isNaN(Number(this._distance)) && this._bufferTools.value ? this._bufferTools.value.distance : this._distance;
      this._selectionLabel = hasSketch || hasSelect || hasSearch || !this._selectionLabel ? `${label} ${distance} ${unit}` : this._selectionLabel;
      if (this._labelName.value) {
        this._labelName.value.value = this._selectionLabel;
      }
    }
  }
  async _layerSelectionChange(_evt) {
    if (Array.isArray(_evt.detail) && _evt.detail.length > 0) {
      const layerPromises = _evt.detail.reduce((prev, cur) => {
        if (this.mapView) {
          prev.push(getFeatureLayerView(this.mapView, cur));
        }
        return prev;
      }, []);
      return Promise.all(layerPromises).then((layerViews) => {
        this.layerViews = layerViews.reduce((prev, cur) => {
          if (cur) {
            prev.push(cur);
          }
          return prev;
        }, []);
        this._featuresCollection = {};
        if (this._sketchGraphic) {
          void this._sketchGraphicsChanged({
            detail: {
              graphics: [this._sketchGraphic],
              useOIDs: false
            }
          });
        }
      });
    }
  }
  async _inputLayerSelectionChange(_evt) {
    const id = _evt?.detail?.length > 0 ? _evt.detail[0] : "";
    if (!this.selectLayerView || id !== this.selectLayerView.layer.id) {
      this.selectLayerView = this.mapView && await getFeatureLayerView(this.mapView, id);
      await this._updateLabel();
      this._bufferGeometry ? await this._selectFeatures([this._bufferGeometry]) : await this._highlightWithOIDsOrGeoms();
    }
  }
  async _distanceChanged(detail) {
    if (detail.newValue !== detail.oldValue) {
      this._distance = detail.newValue;
      await this._updateLabel();
    }
  }
  async _selectLayerFeatures(geom) {
    this._selectionLoading = true;
    const queryFeaturePromises = this.layerViews.map((layerView) => {
      this._featuresCollection[layerView.layer.id] = [];
      return queryFeaturesByGeometry(0, layerView.layer, geom, this._featuresCollection);
    });
    return Promise.all(queryFeaturePromises).then(async (response) => {
      this._selectionLoading = false;
      let graphics = [];
      response.forEach((r) => {
        Object.keys(r).forEach((k) => {
          graphics = graphics.concat(r[k]);
        });
      });
      let hasOID = false;
      graphics.forEach((g) => {
        const geom2 = g.geometry;
        g.symbol = geom2 && geom2.type === "point" ? this.sketchPointSymbol : geom2 && geom2.type === "polyline" ? this.sketchLineSymbol : geom2 && geom2.type === "polygon" ? this.sketchPolygonSymbol : void 0;
        hasOID = g?.layer?.hasOwnProperty("objectIdField") || g.hasOwnProperty("getObjectId");
      });
      const layerViewLayer = this.layerViews[0].layer;
      const selectLayerViewLayer = this.selectLayerView?.layer;
      const useOIDs = hasOID && layerViewLayer.url === selectLayerViewLayer?.url && selectLayerViewLayer?.layerId === layerViewLayer.layerId;
      await this._sketchGraphicsChanged({
        detail: {
          graphics,
          useOIDs
        }
      }, true);
    });
  }
  _useLayerFeaturesEnabledChanged() {
    this.useLayerFeaturesEnabled = !this.useLayerFeaturesEnabled;
    if (this._sketchGraphic) {
      void this._sketchGraphicsChanged({
        detail: {
          graphics: [this._sketchGraphic],
          useOIDs: false
        }
      });
    }
  }
}
customElement("map-select-tools", MapSelectTools);
export {
  MapSelectTools
};
