/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
import { c as h } from "../../chunks/runtime.js";
import { css as m, html as n } from "lit";
import "@arcgis/core/core/Collection.js";
import F from "@arcgis/core/popup/Feature.js";
import _ from "@arcgis/core/Graphic.js";
import y from "@arcgis/core/symbols/SimpleFillSymbol.js";
import { LitElement as A, renderElement as p } from "@arcgis/lumina";
import { a as w } from "../../chunks/maybe.js";
import { usePropertyChange as f, bypassReadOnly as d } from "@arcgis/lumina/controllers";
import { getDisplayedSymbol as I } from "@arcgis/core/symbols/support/symbolUtils.js";
import { g as v } from "../../chunks/feature-utils.js";
import { i as b } from "../../chunks/async-utils.js";
import { stripHTML as S } from "@arcgis/core/applications/Components/stringUtils.js";
import { watch as l } from "@arcgis/core/core/reactiveUtils.js";
const x = m`calcite-notice{padding:var(--calcite-space-lg)}`;
class C extends A {
  constructor() {
    super(...arguments), this._aggregatedGraphicsSet = /* @__PURE__ */ new Set(), this.aggregatedFeatureCount = 0, this.selectedAggregatedFeatureIndex = -1, this.aggregatedFeatureItems = [], this.aggregatedFeatures = [], this.autoDestroyDisabled = !1, this.loading = !1, this.selectedAggregateBoundaryFeature = new _({
      symbol: new y({
        outline: {
          width: 1.5,
          color: "cyan"
        },
        style: "none"
      })
    }), this.arcgisPropertyChange = f()("aggregatedFeatureCount", "selectedAggregatedFeatureIndex", "aggregatedFeatureItems", "aggregatedFeatures", "loading"), this._renderableAggregatedFeatureItems = [];
  }
  static {
    this.properties = { _abortController: 16, aggregatedFeatureCount: 32, selectedAggregatedFeatureIndex: 32, aggregatedFeatureItems: 32, aggregatedFeatures: 32, autoDestroyDisabled: 5, feature: 0, flowItems: 0, loading: 32, map: 0, messages: 0, selectedAggregateBoundaryFeature: 32, spatialReference: 0, timeZone: 1, view: 0 };
  }
  static {
    this.styles = x;
  }
  async destroy() {
    await this.manager.destroy(), this._cancelQuery(), this._clearAggregatedFeatureItems(), this._removeAggregateBoundaryFeature();
  }
  async next() {
    await this._selectRelativeAggregatedFeature(1);
  }
  async previous() {
    await this._selectRelativeAggregatedFeature(-1);
  }
  loaded() {
    this.manager.onLifecycle(() => [
      l(() => [this.feature, this.view], () => {
        this._updateAggregatedFeatures();
      }, { initial: !0 }),
      l(() => this._getAggregatedFeatureItemsHeadingSignature(), () => this.requestUpdate()),
      l(() => this.flowItems?.length, () => {
        const { flowItems: e } = this, r = e?.getItemAt((e.length ?? 0) - 1)?.graphic ?? void 0;
        this._setSelectedAggregatedFeatureIndex(r ? this.aggregatedFeatures.indexOf(r) : -1), this._removeSelectedAggregatedFeature(), r && this._aggregatedGraphicsSet.has(r) && this._addSelectedAggregatedFeature(r);
      })
    ]);
  }
  disconnectedCallback() {
    super.disconnectedCallback(), this._cancelQuery(), this._clearAggregatedFeatureItems(), this._removeAggregateBoundaryFeature();
  }
  _setAggregatedFeatureCount(e) {
    d(() => this.aggregatedFeatureCount = e);
  }
  _setSelectedAggregatedFeatureIndex(e) {
    d(() => this.selectedAggregatedFeatureIndex = e);
  }
  _setAggregatedFeatureItemsReadOnly(e) {
    d(() => {
      this.aggregatedFeatureItems = e;
    }), this._renderableAggregatedFeatureItems = e.filter((t) => !!t.graphic);
  }
  _setAggregatedFeatures(e) {
    this._aggregatedGraphicsSet = new Set(e), d(() => this.aggregatedFeatures = e);
  }
  _getAggregatedFeatureItemsHeadingSignature() {
    let e = "";
    for (const t of this.aggregatedFeatureItems)
      e += `${t.heading ?? ""}|`;
    return e;
  }
  _setLoading(e) {
    d(() => this.loading = e);
  }
  _cancelQuery() {
    this._abortController = w(this._abortController), this._setLoading(!1);
  }
  _removeBoundaryGraphicFromView(e) {
    e?.graphics.remove(this.selectedAggregateBoundaryFeature);
  }
  _clearAggregatedFeatureItems() {
    this._setAggregatedFeatureItemsReadOnly([]), this._setSelectedAggregatedFeatureIndex(-1), this._removeSelectedAggregatedFeature();
  }
  _resetAggregatedFeaturesState() {
    this._setAggregatedFeatures([]), this._clearAggregatedFeatureItems(), this._setAggregatedFeatureCount(0), this._removeAggregateBoundaryFeature();
  }
  _setAggregatedFeatureItems(e) {
    this._setAggregatedFeatureItemsReadOnly(e.map((t) => new F({ graphic: t })));
  }
  _setAggregatedFeaturesState(e) {
    this._setAggregatedFeatures(e), this._setAggregatedFeatureItems(e), this._setAggregatedFeatureCount(e.length);
  }
  _removeAggregateBoundaryFeature() {
    this._removeBoundaryGraphicFromView(this._boundaryGraphicView), this.selectedAggregateBoundaryFeature.geometry = null, this._boundaryGraphicView = void 0;
  }
  _updateAggregateBoundaryFeature(e) {
    const { view: t } = this, r = this._boundaryGraphicView;
    if (!t) {
      this._removeAggregateBoundaryFeature();
      return;
    }
    r !== t && this._removeBoundaryGraphicFromView(r), this.selectedAggregateBoundaryFeature.geometry = e, this._boundaryGraphicView = t, t.graphics.includes(this.selectedAggregateBoundaryFeature) || t.graphics.add(this.selectedAggregateBoundaryFeature);
  }
  async _getLayerViewAndQuery(e) {
    const { view: t } = this, r = v(e);
    if (!t || !r)
      return null;
    const a = await t.whenLayerView(r);
    if (!a?.createQuery || !a?.queryFeatures || !a?.queryExtent)
      return null;
    const g = a.createQuery(), i = e.getObjectId();
    return g.aggregateIds = i != null ? [i] : [], [a, g];
  }
  async _updateAggregatedFeatures() {
    this._cancelQuery();
    const { feature: e } = this;
    if (!e?.isAggregate) {
      this._resetAggregatedFeaturesState();
      return;
    }
    const t = await this._getLayerViewAndQuery(e);
    if (!t) {
      this._resetAggregatedFeaturesState();
      return;
    }
    const [r, s] = t, a = new AbortController();
    this._abortController = a, this._setLoading(!0);
    try {
      const [g, i] = await Promise.all([
        r.queryFeatures(s, { signal: a.signal }),
        r.queryExtent(s, { signal: a.signal })
      ]);
      if (this._abortController !== a || a.signal.aborted)
        return;
      this._abortController = null, this._setLoading(!1);
      const o = g.features ?? [];
      this._setAggregatedFeaturesState(o), i.extent ? this._updateAggregateBoundaryFeature(i.extent) : this._removeAggregateBoundaryFeature();
    } catch (g) {
      if (this._abortController !== a || (this._abortController = null, this._setLoading(!1), b(g)))
        return;
      this._resetAggregatedFeaturesState();
    }
  }
  _addFlowItem(e) {
    e && this.flowItems?.push(e);
  }
  async _addSelectedAggregatedFeature(e) {
    const { view: t } = this;
    if (e && t) {
      const r = await I(e), s = e.clone();
      s.symbol = r, this._selectedAggregatedFeature = s, t.graphics.add(this._selectedAggregatedFeature);
    }
  }
  _removeSelectedAggregatedFeature() {
    this._selectedAggregatedFeature && this.view && (this.view.graphics.remove(this._selectedAggregatedFeature), this._selectedAggregatedFeature = void 0);
  }
  async _selectFeature(e) {
    const { flowItems: t, view: r } = this;
    t && this._addFlowItem(p(n`<arcgis-feature-next .autoDestroyDisabled=${this.autoDestroyDisabled} .flowItems=${t} .graphic=${e.graphic} .map=${this.map} .spatialReference=${this.spatialReference} .timeZone=${this.timeZone} .view=${r ?? void 0}></arcgis-feature-next>`));
  }
  async _selectRelativeAggregatedFeature(e) {
    const { aggregatedFeatures: t, aggregatedFeatureItems: r, flowItems: s } = this;
    if (!s || t.length === 0 || r.length === 0)
      return;
    const a = t.length;
    let g = this.selectedAggregatedFeatureIndex >= 0 && this.selectedAggregatedFeatureIndex < a ? this.selectedAggregatedFeatureIndex : -1;
    if (g === -1) {
      const u = s.getItemAt(s.length - 1)?.graphic;
      g = u ? t.indexOf(u) : -1;
    }
    const i = g === -1 ? e > 0 ? 0 : a - 1 : (g + e + a) % a, o = r[i];
    if (!o?.graphic)
      return;
    this._setSelectedAggregatedFeatureIndex(i);
    const c = s.getItemAt(s.length - 1);
    if (c?.flowType === "feature") {
      c.graphic = o.graphic, this._removeSelectedAggregatedFeature(), await this._addSelectedAggregatedFeature(o.graphic);
      return;
    }
    await this._selectFeature(o);
  }
  _renderChevronIconNode() {
    return n`<calcite-icon flip-rtl icon=chevron-right scale=s slot=content-end></calcite-icon>`;
  }
  render() {
    const { _renderableAggregatedFeatureItems: e } = this, { loading: t } = this;
    return t || e.length > 0 ? n`<calcite-list .loading=${t} display-mode=flat .label=${this.messages?.aggregatedFeatures ?? ""} selection-mode=none>${e.map((s) => n`<calcite-list-item .label=${s.heading ? S(s.heading) : void 0} @calciteListItemSelect=${() => this._selectFeature(s)}>${this._renderChevronIconNode()}</calcite-list-item>`)}</calcite-list>` : n`<calcite-notice icon=information kind=brand open scale=s width=full><div slot=message>${this.messages?.noAggregatedFeatures}</div></calcite-notice>`;
  }
}
h("arcgis-aggregated-features", C);
export {
  C as ArcgisAggregatedFeatures
};
