/* COPYRIGHT Esri - https://js.arcgis.com/1.2/LICENSE.txt */
import { c as customElement } from "../../chunks/runtime.js";
import { d as getMapLayerHash, a as getAllFeatureLayers, c as getFeatureLayerView } from "../../chunks/mapViewUtils.js";
import * as intl from "@arcgis/core/intl";
import { u as useT9n } from "../../chunks/useT9n.js";
import { css, html } from "lit";
import { LitElement, createEvent, noShadowRoot } from "@arcgis/lumina";
import * as reactiveUtils from "@arcgis/core/core/reactiveUtils";
async function formatNumber(number, options) {
  const { style = "decimal", places = 2 } = options || {};
  const numberFormatIntlOptions = intl.convertNumberFormatToIntlOptions({
    places,
    digitSeparator: true
  });
  numberFormatIntlOptions.style = style;
  return intl.formatNumber(number, numberFormatIntlOptions);
}
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;
}

.notice-msg {
  width: calc(100% - 20px);
  padding: 10px;
}

.layer-name {
  font-weight: 500;
  word-break: break-word;
}

.feature-count {
  padding: 0 10px;
}
}`;
class LayerList extends LitElement {
  constructor() {
    super();
    this.layers = [];
    this.showFeatureCount = true;
    this.showNextIcon = false;
    this.applyLayerViewFilter = false;
    this.filterByMapExtent = false;
    this._noLayersToDisplay = false;
    this._mapLayerIds = [];
    this._isLoading = false;
    this._translations = useT9n({ name: "layer-list", blocking: true });
    this.layerSelect = createEvent();
    this.layersListLoaded = createEvent();
    this.listenOn(window, "selectedLanguageUpdated", this.selectedLanguageUpdated);
  }
  static {
    this.properties = { mapView: [0, {}, { attribute: false }], layers: [0, {}, { attribute: false }], showFeatureCount: [5, {}, { type: Boolean }], showNextIcon: [5, {}, { type: Boolean }], applyLayerViewFilter: [5, {}, { type: Boolean }], filterByMapExtent: [5, {}, { type: Boolean }], _noLayersToDisplay: [16, {}, { state: true }], _mapLayerIds: [16, {}, { state: true }], _isLoading: [16, {}, { state: true }], _translations: [16, {}, { state: true }] };
  }
  static {
    this.styles = styles;
  }
  static {
    this.shadowRootOptions = noShadowRoot;
  }
  willUpdate(changes) {
    if (changes.has("filterByMapExtent") && this.hasUpdated) {
      this.filterByMapExtentWatchHandler(this.filterByMapExtent);
    }
  }
  filterByMapExtentWatchHandler(enabled) {
    if (enabled) {
      this.initializeMapExtentFilter();
    } else if (this._filterByMapExtentHandle) {
      this._filterByMapExtentHandle.remove();
    }
  }
  async refresh() {
    await this.setLayers();
  }
  async selectedLanguageUpdated(_evt) {
    await this.setLayers();
  }
  async load() {
    if (this.filterByMapExtent) {
      this.initializeMapExtentFilter();
    }
  }
  async loaded() {
    await this.setLayers();
  }
  render() {
    return html`${this._isLoading && html`<calcite-loader label scale=m></calcite-loader>` || ""}${!this._isLoading && this.mapView && this._noLayersToDisplay && html`<calcite-notice class="notice-msg" icon=layers-reference kind=danger open><div slot=title>${this._translations.error}</div><div slot=message>${this._translations.noLayerToDisplayErrorMsg}</div></calcite-notice>` || ""}${!this._isLoading && this.mapView && html`<calcite-list label selection-appearance=border selection-mode=none>${this.filterByMapExtent && this._mapLayerIds.length > 0 && this.getExtentNotice() || ""}${this.renderLayerList()}</calcite-list>` || ""}`;
  }
  initializeMapExtentFilter() {
    this._filterByMapExtentHandle = reactiveUtils.when(() => this.mapView?.stationary, () => {
      void this.setLayers();
    }, {
      initial: true
    });
  }
  async setLayers() {
    if (this.mapView) {
      this._isLoading = true;
      await this.initLayerHash();
      this._isLoading = false;
    }
  }
  async initLayerHash() {
    const def = [];
    if (this.mapView) {
      this._layerItemsHash = await getMapLayerHash(this.mapView, true);
      const allMapLayers = await getAllFeatureLayers(this.mapView);
      for (const eachLayer of allMapLayers) {
        if (eachLayer?.type === "feature") {
          if (this.showFeatureCount) {
            const q = eachLayer.createQuery();
            if (eachLayer?.definitionExpression) {
              q.where = q.where + " AND " + eachLayer.definitionExpression;
            }
            if (this.applyLayerViewFilter) {
              const featureLayerView = await getFeatureLayerView(this.mapView, eachLayer.id);
              if (featureLayerView?.filter?.where) {
                q.where = q.where ? q.where + " AND " + featureLayerView.filter.where : featureLayerView.filter.where;
              }
            }
            q.geometry = this.filterByMapExtent ? this.mapView.extent : null;
            const result = eachLayer.queryFeatureCount(q);
            def.push(result);
            void result.then(async (resCount) => {
              const formattedCount = !Number.isNaN(resCount) ? await formatNumber(resCount, {
                places: 0,
                style: "decimal"
              }) : "";
              if (this._layerItemsHash) {
                this._layerItemsHash[eachLayer.id].formattedFeatureCount = formattedCount;
              }
            });
          }
        }
      }
      await Promise.all(def).then(() => {
        const editableLayerIds = this._layerItemsHash && this.getLayersToBeShownInList(this._layerItemsHash);
        this._mapLayerIds = editableLayerIds?.reverse() || [];
        this.handleNoLayersToDisplay();
      }, () => {
        this._mapLayerIds = [];
        this.handleNoLayersToDisplay();
      });
    }
  }
  handleNoLayersToDisplay() {
    this._noLayersToDisplay = !(this._mapLayerIds.length > 0);
    this.layersListLoaded.emit(this._mapLayerIds);
  }
  getLayersToBeShownInList(hash) {
    const configuredLayers = this.layers?.length > 0 ? this.layers : [];
    return Object.keys(hash).reduce((prev, cur) => {
      if (configuredLayers.indexOf(cur) > -1) {
        prev.push(cur);
      }
      return prev;
    }, []);
  }
  renderLayerList() {
    return this._mapLayerIds.length > 0 ? this._mapLayerIds.reduce((prev, layerId) => {
      if (this._layerItemsHash && this._layerItemsHash[layerId]) {
        const li = this.getLayerListItem(layerId);
        if (li) {
          prev.push(li);
        }
      }
      return prev;
    }, []) : void 0;
  }
  getLayerListItem(layerId) {
    const layerName = this._layerItemsHash && this._layerItemsHash[layerId].name;
    const featureCount = this._layerItemsHash && this._layerItemsHash[layerId].formattedFeatureCount;
    return html`<calcite-list-item @calciteListItemSelect=${() => {
      this.onLayerItemSelected(layerId);
    }}><div class="layer-name" slot=content-start>${layerName}</div>${this.showFeatureCount && featureCount !== void 0 && featureCount !== "" && html`<div class="feature-count" slot=content-end>${`(${featureCount})`}</div>` || ""}${this.showNextIcon && html`<calcite-icon flip-rtl icon=chevron-right scale=s slot=content-end></calcite-icon>` || ""}</calcite-list-item>`;
  }
  getExtentNotice() {
    return html`<calcite-notice class="notice-msg" icon=extent-filter kind=brand open scale=s><div slot=message>${this._translations.extentFilterMsg}</div></calcite-notice>`;
  }
  onLayerItemSelected(layerId) {
    if (this._layerItemsHash) {
      this.layerSelect.emit({ layerId, layerName: this._layerItemsHash[layerId]?.name });
    }
  }
}
customElement("layer-list", LayerList);
export {
  LayerList
};
