/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
import { c as m } from "../../chunks/runtime.js";
import { g as y, d as b, f } from "../../chunks/mapViewUtils.js";
import { u as _ } from "../../chunks/useT9n.js";
import { css as u, html as i, nothing as l } from "lit";
import { createRef as o, ref as d } from "lit-html/directives/ref.js";
import { LitElement as g, createEvent as n, noShadowRoot as L, safeStyleMap as c, safeClassMap as p } from "@arcgis/lumina";
import { useContextConsumer as w } from "@arcgis/lumina/context";
import { p as v } from "../../chunks/publicNotificationContext.js";
const I = u`@layer{:host{display:block}.map-layer-picker-container{width:100%;align-items:center}.map-layer-picker{position:relative;width:100%;display:inline-block}.padding-bottom-1{padding-bottom:1rem}.layer-picker-dropdown{height:100%;width:100%}.max-width-350{max-width:350px}.height-100{height:100%}.disabled{cursor:default!important;user-select:none;opacity:var(--calcite-opacity-disabled);pointer-events:none}.no-bottom-margin{--calcite-label-margin-bottom: 0px}.layer-picker-label-container{align-items:center;display:inline-flex;height:100%;padding-inline-start:1rem;padding-inline-end:1rem}.padding-start-1{padding-inline-start:1rem}.cursor-default{cursor:default}.popover-list{overflow:auto;width:250px}}`;
class $ extends g {
  constructor() {
    super(), this.appearance = "transparent", this.configLayerOrderDefined = !1, this.defaultLayerId = "", this.disabled = !1, this.display = "inline-block", this.enabledLayerIds = [], this.isMobile = !1, this.showOnlyUpdatableLayers = !1, this.selectedIds = [], this.scale = "m", this.showTables = !1, this.showTablesDisabled = !1, this.showSingleLayerAsLabel = !1, this.type = "select", this.showLayersListInPopover = !1, this.referenceElement = "", this.force = !1, this._hasMultipleLayers = !0, this._hasValidLayers = !0, this._isDropdownOpen = !1, this.ids = [], this.selectedName = "", this._translations = _({ name: "map-layer-picker", blocking: !0 }), this.defaultLayerHonored = !1, this._layerSelectElement = o(), this._layerComboboxElement = o(), this._pnContextConsumer = w({
      context: v,
      subscribe: !0
    }), this._skipEditCheck = !1, this._popover = o(), this.beforeLayerSelectionChange = n(), this.idsFound = n(), this.noLayersFound = n(), this.layerSelectionChange = n(), this.listenOn(window, "mapChanged", this.mapChanged), this.listenOn(window, "requestLayerSelectionChange", this.requestLayerSelectionChange);
  }
  static {
    this.properties = { appearance: 1, configLayerOrderDefined: 5, defaultLayerId: 1, disabled: 5, display: 1, enabledLayerIds: 0, height: 9, isMobile: 5, mapView: 0, showOnlyUpdatableLayers: 5, placeholderIcon: 1, selectedIds: 0, scale: 1, showTables: 5, showTablesDisabled: 5, showSingleLayerAsLabel: 5, type: 1, showLayersListInPopover: 5, referenceElement: 1, force: 16, _hasMultipleLayers: 16, _hasValidLayers: 16, _isDropdownOpen: 16, ids: 16, selectedName: 16, _translations: 16 };
  }
  static {
    this.styles = I;
  }
  static {
    this.shadowRootOptions = L;
  }
  willUpdate(e) {
    e.has("mapView") && this.hasUpdated && this.mapViewWatchHandler(), e.has("type") && (this._layerElement = this.type === "select" ? this._layerSelectElement : this._layerComboboxElement), e.has("selectedIds") && this.hasUpdated && this.mapView && (async () => {
      const t = await y(this.mapView, this.selectedIds[0]);
      this.selectedName = t?.title ?? "";
    })(), e.has("enabledLayerIds") && this.hasUpdated && this.enabledLayerIdsWatchHandler();
  }
  async enabledLayerIdsWatchHandler() {
    const e = this.selectedIds.length > 0 && !this.enabledLayerIds.includes(this.selectedIds[0]), t = this.enabledLayerIds.some((a) => !this.ids.includes(a)), s = this.ids.toString() !== this.enabledLayerIds.toString();
    e ? this.mapViewWatchHandler() : (t || s) && this._setLayers(), this._hasMultipleLayers = this.enabledLayerIds.length > 1;
  }
  async mapViewWatchHandler() {
    if (await this._setLayers(), this.ids?.length > 0) {
      this._hasValidLayers = !0, this._hasMultipleLayers = this.ids.length > 1;
      let e = this.ids[0];
      this.defaultLayerId && !this.defaultLayerHonored && (e = this.defaultLayerId), await this._setSelectedLayer(e);
    } else this.mapView && (this._hasValidLayers = !1, this.noLayersFound.emit());
  }
  async setLayerById(e, t = !1) {
    this._skipEditCheck = t, !t || t && e !== this.selectedIds[0] ? this._setSelectedLayer(e) : t && e === this.selectedIds[0] && (this.force = !0, setTimeout(() => {
      this.force = !1;
    }, 10)), this._skipEditCheck = !1;
  }
  async setLayerByIds(e, t = !1) {
    this._skipEditCheck = t, this._layerSelectionChange(e), this._skipEditCheck = !1;
  }
  async updateLayer() {
    await this._setSelectedLayer(this.ids[0]);
  }
  async mapChanged(e) {
    const t = e.detail.isValid;
    t && !this._hasValidLayers ? await this.load() : t || (this._hasValidLayers = !1, this.noLayersFound.emit());
  }
  async requestLayerSelectionChange(e) {
    const t = e.detail;
    await this._setSelectedLayer(t);
  }
  async load() {
    await this._setLayers(), this.ids?.length > 0 ? (this._hasValidLayers = !0, this._hasMultipleLayers = this.ids.length > 1, this.defaultLayerId || await this._setSelectedLayer(this.ids[0])) : this.mapView && (this._hasValidLayers = !1, this.noLayersFound.emit());
  }
  render() {
    const e = "map-layer-picker";
    let t = this.height && this.height > 0 && !this.showLayersListInPopover ? { height: `${this.height.toString()}px` } : {};
    return t = { ...t, display: this.display }, i`<div class="map-layer-picker-container" style=${c(t)}><div class="map-layer-picker" style=${c(t)}>${this._hasValidLayers ? !this._hasMultipleLayers && this.showSingleLayerAsLabel ? this._getSingleLayerPlaceholder() : this.type === "combobox" ? this._getCombobox(e) : this.type === "select" ? this._getSelect(e) : this.showLayersListInPopover ? this._getMapLayerPopOver() : this._getDropdown(e) : this._getInvalidPlaceholder()}</div></div>`;
  }
  loaded() {
    if (this.ids?.length > 0 || this.selectedIds?.length === 1) {
      const e = this.selectedIds.length === 1 ? this.selectedIds[0] : this.ids[0];
      this.type === "select" ? this._layerElement.value && (this._layerElement.value.value = e) : this.type === "dropdown" && (this.selectedName = this._layerNameHash && Object.keys(this._layerNameHash).indexOf(e) > -1 ? this._layerNameHash[e].name : this._tableNameHash && Object.keys(this._tableNameHash).indexOf(e) > -1 ? this._tableNameHash[e].name : "");
    }
    this._popover.value?.addEventListener("calcitePopoverOpen", () => {
      this.el.querySelector("calcite-dropdown-item[selected]")?.setFocus();
    });
  }
  _getMapLayerPopOver() {
    const e = this.height && this.height > 0 ? { "max-height": `${this.height.toString()}px` } : {};
    return i`<calcite-popover auto-close focus-trap-disabled .label=${this.referenceElement} placement=left .referenceElement=${this.referenceElement} scale=s ${d(this._popover)}><div class=popover-list style=${c(e)}>${this._getMapLayerOptions()}</div></calcite-popover>`;
  }
  _getInvalidPlaceholder() {
    return i`<div><calcite-notice class="height-100" icon=exclamation-mark-triangle id=no-valid-layers kind=danger open><div slot=message>${this._translations.noLayersFound}</div></calcite-notice><calcite-tooltip .label=${this._translations.enableEditUpdate} placement=bottom reference-element=no-valid-layers><span>${this._translations.enableEditUpdate}</span></calcite-tooltip></div>`;
  }
  _getSingleLayerPlaceholder() {
    const e = this._getItemTypeIcon();
    return i`<div class="layer-picker-label-container cursor-default"><calcite-icon aria-hidden=true .icon=${e} scale=s></calcite-icon><calcite-label class="no-bottom-margin padding-start-1">${this.selectedName}</calcite-label></div>`;
  }
  _getSelect(e) {
    return i`<calcite-select .disabled=${this.disabled} id=${e ?? l} label @calciteSelectChange=${() => this._layerSelectionChange()} .scale=${this.scale} ${d(this._layerElement)}>${this._getMapLayerOptions()}</calcite-select>`;
  }
  _getCombobox(e) {
    return i`<calcite-combobox clear-disabled id=${e ?? l} label @calciteComboboxChange=${() => this._layerSelectionChange()} .placeholderIcon=${this.placeholderIcon} .scale=${this.scale} selection-mode=single ${d(this._layerElement)}>${this._getMapLayerOptions()}</calcite-combobox>`;
  }
  _getDropdown(e) {
    return i`<calcite-dropdown class="layer-picker-dropdown" @calciteDropdownBeforeClose=${() => this._isDropdownOpen = !1} @calciteDropdownBeforeOpen=${() => this._isDropdownOpen = !0}>${this.isMobile ? this._getDropdownButton() : this._getActionDropdownButton(e)}<calcite-dropdown-group selection-mode=single>${this._getMapLayerOptions()}</calcite-dropdown-group></calcite-dropdown>`;
  }
  _getActionDropdownButton(e) {
    return i`<calcite-action id=${e ?? l} slot=trigger .text=${this.selectedName}>${this._getDropdownButton()}</calcite-action>`;
  }
  _getDropdownButton() {
    const e = this._getItemTypeIcon(), t = this.isMobile ? "" : "max-width-350", s = this.isMobile ? "trigger" : "", a = this._isDropdownOpen ? "chevron-up" : "chevron-down";
    return i`<calcite-button alignment=icon-end-space-between .appearance=${this.appearance} class=${p(t)} .iconEnd=${a} .iconStart=${e} kind=neutral slot=${s ?? l} width=full><div>${this.selectedName}</div></calcite-button>`;
  }
  _getItemTypeIcon() {
    const e = this.selectedIds.length > 0 && this._layerNameHash, t = e ? this.selectedIds[0] : void 0;
    return e ? Object.keys(this._layerNameHash).indexOf(t) > -1 ? "layers" : "table" : "layers";
  }
  _getMapLayerOptions() {
    return this.ids.reduce((e, t) => (this._validLayer(t) ? e.push(this._getItem(t, "layer")) : this._validTable(t) && e.push(this._getItem(t, "table")), e), []);
  }
  _getItem(e, t) {
    const s = t === "layer" && this._layerNameHash ? this._layerNameHash[e] : this._tableNameHash ? this._tableNameHash[e] : void 0, a = this.showOnlyUpdatableLayers ? s && !s.supportsUpdate : !1, h = s?.name || "", r = this.selectedIds.indexOf(e) > -1;
    return this.type === "combobox" ? i`<calcite-combobox-item .disabled=${a} .heading=${h} .selected=${r} .value=${e}></calcite-combobox-item>` : this.type === "select" ? i`<calcite-option .disabled=${a} .label=${h} .selected=${r} .value=${e}></calcite-option>` : this.force && r || !this.force ? i`<calcite-dropdown-group class=${p(a ? "disabled" : "")} id=${h ?? l} .selectionMode=${a ? "none" : "single"}><calcite-dropdown-item .disabled=${!!(t === "table" && this.showTablesDisabled)} .iconStart=${t} @click=${a ? void 0 : () => {
      this._setSelectedLayer(e);
    }} .selected=${r}>${h}</calcite-dropdown-item></calcite-dropdown-group>` : null;
  }
  async _setSelectedLayer(e) {
    if (e !== this.selectedIds[0]) {
      let t;
      if (this.defaultLayerId && !this.defaultLayerHonored && (t = this._getLayerFromHash(this.defaultLayerId), this.defaultLayerHonored = t !== void 0, e = this.defaultLayerHonored ? this.defaultLayerId : e), t = t || this._getLayerFromHash(e), !this._skipEditCheck && this.beforeLayerSelectionChange.emit({
        currentId: this.selectedIds[0],
        newId: e,
        ref: this.el
      }).defaultPrevented)
        return;
      this.selectedName = t?.name, this.selectedIds = [e], this._popover.value && (this._popover.value.open = !1), this.layerSelectionChange.emit(this.selectedIds);
    } else {
      const t = this.mapView && await y(this.mapView, this.selectedIds[0]);
      this.selectedName = t?.title || "";
    }
  }
  _getLayerFromHash(e) {
    return this._layerNameHash && Object.keys(this._layerNameHash).indexOf(e) > -1 ? this._layerNameHash[e] : this._tableNameHash && Object.keys(this._tableNameHash).indexOf(e) > -1 ? this._tableNameHash[e] : void 0;
  }
  async _setLayers() {
    if (this.mapView) {
      await this._initLayerTableHash();
      let e = [];
      this._layerNameHash && (e = this.showOnlyUpdatableLayers ? this._getEditableIds(this._layerNameHash) : Object.keys(this._layerNameHash));
      let t = [];
      if (this._tableNameHash && (t = this.showTables ? this.showOnlyUpdatableLayers ? this._getEditableIds(this._tableNameHash) : Object.keys(this._tableNameHash) : []), this.configLayerOrderDefined) {
        const s = [...e.reverse(), ...t.reverse()];
        this.ids = this.enabledLayerIds.length > 0 ? this.enabledLayerIds.filter((a) => s.includes(a)) : s;
      } else
        this.ids = [
          ...e.reverse().filter((s) => this.enabledLayerIds?.length > 0 ? this.enabledLayerIds.indexOf(s) > -1 : !0),
          ...t.reverse().filter((s) => this.enabledLayerIds?.length > 0 ? this.enabledLayerIds.indexOf(s) > -1 : !0)
        ];
      this.idsFound.emit(this.ids);
    }
  }
  _getEditableIds(e) {
    return Object.keys(e).filter((t) => e[t].supportsUpdate);
  }
  async _initLayerTableHash() {
    this._layerNameHash = this.mapView && await b(this.mapView, this.showOnlyUpdatableLayers), this._tableNameHash = this.showTables && this.mapView ? await f(this.mapView, this.showOnlyUpdatableLayers) : {};
  }
  _validLayer(e) {
    const t = this._pnContextConsumer.value, s = this._layerNameHash && this._layerNameHash[e]?.name;
    return s !== void 0 && Object.keys(t?.managedLayers || []).indexOf(s) < 0 && (this.enabledLayerIds?.length > 0 ? this.enabledLayerIds.indexOf(e) > -1 : !0);
  }
  _validTable(e) {
    const t = this._pnContextConsumer.value, s = this._tableNameHash && this._tableNameHash[e]?.name, a = s && this.showTables;
    return a ? (t?.managedTables || []).indexOf(s) < 0 && (this.enabledLayerIds?.length > 0 ? this.enabledLayerIds.indexOf(e) > -1 : !0) : a !== void 0;
  }
  _layerSelectionChange(e) {
    if (this._layerElement.value) {
      const t = e || (Array.isArray(this._layerElement.value.value) ? this._layerElement.value.value : [this._layerElement.value.value]);
      if (JSON.stringify(t) !== JSON.stringify([""])) {
        if (JSON.stringify(t) === JSON.stringify(this.selectedIds) || !this._skipEditCheck && this.beforeLayerSelectionChange.emit({
          currentIds: this.selectedIds,
          newIds: t,
          ref: this.el
        }).defaultPrevented)
          return;
        this.selectedIds = t, this.layerSelectionChange.emit(this.selectedIds);
      }
    }
  }
}
m("map-layer-picker", $);
export {
  $ as MapLayerPicker
};
