/* COPYRIGHT Esri - https://js.arcgis.com/5.0/LICENSE.txt */
import { c as f } from "../../chunks/runtime.js";
import { queryAllJSON as b } from "@arcgis/core/applications/Components/featureUtils.js";
import v from "@arcgis/core/Color.js";
import "@arcgis/core/core/Error.js";
import "@arcgis/core/Graphic.js";
import $ from "@arcgis/core/rest/support/FeatureSet.js";
import { LitElement as F, createEvent as n } from "@arcgis/lumina";
import { log as u, composeMissingPropertyMessage as m, composeEmptyPropertyMessage as w } from "@arcgis/toolkit/log";
import { css as L, html as r } from "lit";
import { u as C } from "../../chunks/useT9n.js";
import { h as y } from "../../chunks/feature-utils.js";
import { createRef as R, ref as g } from "lit/directives/ref.js";
const T = L`:host{min-height:var(--arcgis-internal-panel-height-sm, 240px);height:100%}arcgis-features{height:100%}calcite-flow{min-height:var(--arcgis-internal-panel-height-sm, 240px);height:100%}calcite-table{--calcite-table-border-color: none}calcite-table-row{--calcite-table-row-border-color: var(--calcite-color-border-3)}.white-panel-background{--calcite-panel-background-color: var(--calcite-color-foreground-1)}.aggregated-geometry-container{display:flex;justify-content:space-between;padding:0 var(--calcite-spacing-md) var(--calcite-spacing-md) var(--calcite-spacing-md)}#elements-list-item{border:solid 1px var(--calcite-color-border-3);border-radius:var(--calcite-corner-radius-sm);margin:0 var(--calcite-spacing-sm)}.no-selectable-results{padding:0 var(--calcite-spacing-md);color:var(--calcite-color-text-3);font-size:var(--calcite-font-size)}.results-heading{display:flex;flex-direction:column;margin:var(--calcite-spacing-md);gap:var(--calcite-spacing-xs)}.results-heading .results-heading-title{font-weight:var(--calcite-font-weight-medium);font-size:var(--calcite-font-size);color:var(--calcite-color-text-1)}.results-heading .results-heading-subtitle{font-size:var(--calcite-font-size--1);color:var(--calcite-color-text-3)}.functions-heading{padding:var(--calcite-spacing-md) var(--calcite-spacing-md) var(--calcite-spacing-xxs) var(--calcite-spacing-md);font-weight:var(--calcite-font-weight-medium);font-size:var(--calcite-font-size);color:var(--calcite-color-text-1)}.no-results-landing{display:flex;flex-direction:column;justify-content:center;align-items:center;text-align:center;margin:var(--calcite-spacing-sm) var(--calcite-spacing-xl) var(--calcite-spacing-xl) var(--calcite-spacing-xl);gap:var(--calcite-spacing-md)}.no-results-landing calcite-icon{margin-bottom:var(--calcite-spacing-sm);--calcite-icon-color: var(--calcite-color-text-3)}.no-results-landing .no-results-heading{font-size:var(--calcite-font-size-2)}.no-results-landing .no-results-description{color:var(--calcite-color-text-3)}`, p = {
  dirtyAreasDiscovered: -2147208511,
  noValidControllers: -2147208935
};
class E extends F {
  constructor() {
    super(...arguments), this._defaultPopupTemplateEnabled = !0, this._messages = C({ blocking: !0 }), this._elementsWithoutLayer = [], this._popoverRef = R(), this._featuresFromSelectedLayer = [], this._layerIdToFeatures = /* @__PURE__ */ new Map(), this._layerIdToLayer = /* @__PURE__ */ new Map(), this._subtypeCodeToFeatures = /* @__PURE__ */ new Map(), this._sourceIdToElements = /* @__PURE__ */ new Map(), this._unLayers = [], this._compareByFeatureTitle = (e, t) => e.label.localeCompare(t.label, void 0, { numeric: !0 }), this._compareByLayerTitle = ([, e], [, t]) => {
      const a = e[0].feature.layer, s = t[0].feature.layer, c = a?.title ?? "", l = s?.title ?? "";
      return c.localeCompare(l, void 0, { numeric: !0 });
    }, this._queryFeaturesOnLayer = async ([e, t]) => {
      const a = this.utilityNetwork?.getLayerIdBySourceId(e), s = this._getLayerByLayerId(a), c = this._getElementsUniqueByGlobalId(t);
      if (a == null || !s) {
        this._elementsWithoutLayer.push(...c);
        return;
      }
      const l = s.createQuery();
      l.gdbVersion = this.utilityNetwork?.gdbVersion, l.objectIds = c.map((i) => i.objectId), l.outFields = ["*"];
      const { features: h } = $.fromJSON(await b(s, l)), o = await Promise.all(h.map(async (i) => {
        i.layer = s.type === "subtype-group" ? s.findSublayerForFeature(i) : s, i.origin = i.layer;
        const d = i.layer;
        if (i.getEffectivePopupTemplate(this._defaultPopupTemplateEnabled) || (i.popupTemplate = d.createPopupTemplate()), d && "getFeatureTitle" in d) {
          const _ = await d.getFeatureTitle(i) || y(i);
          return { feature: i, label: _ };
        }
        return { feature: i, label: y(i) };
      }));
      s.type === "subtype-group" ? o.forEach((i) => this._addOrCreateMapValue(this._subtypeCodeToFeatures, i.feature.layer.subtypeCode, i)) : this._layerIdToFeatures.set(a, o);
    }, this._aggregateGeometryRefChange = (e) => {
      e && (this._aggregatedGeometryComponentElement = e);
    }, this._featuresRefChange = (e) => {
      e && (this._featuresComponentElement = e);
    }, this._aggregatedGeometryDisabled = !1, this.aggregatedGeometryGraphicsColor = new v([255, 255, 0, 0.6]), this.hideFeatureResults = !1, this.isElementsSelected = !1, this.layers = [], this.state = "ready", this.traceResultFeatures = [], this.autoDestroyDisabled = !1, this.arcgisAggregatedGeometryGraphicsColorChange = n(), this.arcgisHideGraphicsChange = n(), this.arcgisSelectedLayerChange = n(), this.arcgisSelectedResultTypeChange = n(), this.arcgisTraceResultFeaturesReady = n(), this._renderLayerListItem = ([, e]) => {
      if (!e.length)
        return null;
      const t = e[0].feature.layer, a = t?.title || this._messages.unknown;
      return r`<calcite-list-item .label=${a} @calciteListItemSelect=${() => this._setSelectedLayerAndFeatures(t)}><calcite-chip .label=${this._messages.labels.numElements} slot=content-end scale=s>${e.length}</calcite-chip><calcite-icon icon=chevron-right slot=content-end></calcite-icon></calcite-list-item>`;
    }, this._renderFeatureListItem = (e) => {
      const { feature: t, label: a } = e;
      return r`<calcite-list-item .label=${a} @calciteListItemSelect=${() => this.selectedFeature = t}><calcite-icon icon=chevron-right slot=content-end></calcite-icon></calcite-list-item>`;
    };
  }
  static {
    this.properties = { _aggregatedGeometryDisabled: 16, aggregatedGeometryGraphicsColor: 0, hideFeatureResults: 5, featuresFromSelectedLayer: 32, isElementsSelected: 5, layers: 0, messageOverrides: 0, numResults: 32, referenceElement: 1, selectedFeature: 0, selectedLayer: 0, state: 1, traceConfigTitle: 1, traceError: 0, traceResult: 0, traceResultFeatures: 0, utilityNetwork: 0, view: 0, autoDestroyDisabled: 5 };
  }
  static {
    this.styles = T;
  }
  get featuresFromSelectedLayer() {
    return this._featuresFromSelectedLayer.map(({ feature: e }) => e);
  }
  get numResults() {
    return this.traceResultFeatures.length + this._elementsWithoutLayer.length;
  }
  clearAggregatedGeometryGraphics() {
    this._aggregatedGeometryComponentElement?.destroy();
  }
  async destroy() {
    this._layerIdToFeatures.clear(), this._subtypeCodeToFeatures.clear(), this._sourceIdToElements.clear(), this._aggregatedGeometryComponentElement?.destroy(), this._featuresComponentElement?.destroy(), await this.manager.destroy();
  }
  load() {
    this.traceResult && (this._setSourceIdToElements(), this._loadDependencies().then(() => this._queryTraceResultsFeatures()).finally(() => {
      this.arcgisTraceResultFeaturesReady.emit(), this.state = "ready";
    }));
  }
  willUpdate(e) {
    e.has("isElementsSelected") && this.arcgisSelectedResultTypeChange.emit(), e.has("selectedLayer") && this.arcgisSelectedLayerChange.emit(), e.has("traceResult") && (this.isElementsSelected = !1, this.traceResult || (this.traceResultFeatures = [], this._elementsWithoutLayer = [])), (e.has("layers") || e.has("utilityNetwork")) && this._loadDependencies();
  }
  loaded() {
    this.utilityNetwork || u("warn", this, m("utilityNetwork")), this.layers.length === 0 && u("warn", this, w("layers")), this.view || u("warn", this, m("view"));
  }
  disconnectedCallback() {
    super.disconnectedCallback(), this._layerIdToLayer.clear();
  }
  _addOrCreateMapValue(e, t, a) {
    const s = e.get(t);
    s == null ? e.set(t, [a]) : s.push(a);
  }
  _getLayerByLayerId(e) {
    if (e == null)
      return;
    const { _layerIdToLayer: t, _unLayers: a } = this;
    if (t.get(e))
      return t.get(e);
    const s = a.find((c) => "layerId" in c && c.layerId === e);
    return s && t.set(e, s), s;
  }
  _getElementsUniqueByGlobalId(e) {
    return Array.from(new Map(e.map((t) => [t.globalId, t])).values());
  }
  _handleHideGraphicsChange(e) {
    e.stopPropagation();
    const t = e.detail;
    this.arcgisHideGraphicsChange.emit(t), this._aggregatedGeometryDisabled = t, t && this._popoverRef.value?.open && (this._popoverRef.value.open = !1);
  }
  async _loadDependencies() {
    const { layers: e, utilityNetwork: t } = this;
    if (!t)
      return;
    t.loaded || (this.state = "loading", await t.load()), this._unLayers = e.filter((s) => t.isUtilityLayer(s));
    const a = this._unLayers.filter((s) => !s.loaded).map((s) => s.load());
    a.length > 0 && (this.state = "loading", await Promise.allSettled(a));
  }
  async _queryTraceResultsFeatures() {
    const e = Array.from(this._sourceIdToElements.entries());
    if (!e.length)
      return;
    this.state = "loading";
    const t = e.map(this._queryFeaturesOnLayer);
    (await Promise.allSettled(t)).forEach((l, h) => {
      if (l.status === "rejected") {
        const [o] = e[h];
        u("error", this, `Failed to query features for source ${o}. Reason: ${l.reason}`);
      }
    });
    const s = Array.from(this._layerIdToFeatures.values()), c = Array.from(this._subtypeCodeToFeatures.values());
    this.traceResultFeatures = s.concat(c).flat().map(({ feature: l }) => l);
  }
  _setSelectedLayerAndFeatures(e) {
    let t;
    if (!e)
      t = [];
    else if (e.type === "subtype-sublayer") {
      const { subtypeCode: a } = e;
      t = this._subtypeCodeToFeatures.get(a) ?? [];
    } else {
      const { layerId: a } = e;
      t = this._layerIdToFeatures.get(a) ?? [];
    }
    this._featuresFromSelectedLayer = t.sort(this._compareByFeatureTitle), this.selectedLayer = e;
  }
  _setSourceIdToElements() {
    this.traceResult.elements?.forEach((e) => this._addOrCreateMapValue(this._sourceIdToElements, e.networkSourceId, e));
  }
  render() {
    const { traceError: e, traceResult: t } = this;
    if (e)
      return this._renderErrorLanding(e);
    if (!t)
      return this._renderNoTraceLanding();
    const { elements: a, globalFunctionResults: s, aggregatedGeometry: c } = t;
    if (!a.length && !s.length && !c)
      return this._renderNoResultsLanding();
    if (this.state === "loading")
      return this._renderGettingResults();
    if (this.selectedFeature)
      return r`<arcgis-features .referenceElement=${this.referenceElement} .features=${[this.selectedFeature]} .view=${this.view} open .defaultPopupTemplateEnabled=${this._defaultPopupTemplateEnabled} @arcgisClose=${() => this.selectedFeature = void 0} .autoDestroyDisabled=${this.autoDestroyDisabled} ${g(this._featuresRefChange)}></arcgis-features>`;
    const l = a.length > 0 && !s.length && !c;
    return this.hideFeatureResults && l ? this._renderFeaturesAreHiddenLanding() : r`<calcite-flow>${l ? null : r`<calcite-flow-item .selected=${!this.isElementsSelected}>${this._renderLanding(t)}</calcite-flow-item>`}<calcite-flow-item .heading=${this._messages.headings.features} .description=${this._messages.headings.totalFeatures.replace("{number}", this.numResults.toString())} .selected=${(l || this.isElementsSelected) && !this.selectedLayer} @calciteFlowItemBack=${() => this.isElementsSelected = !1}>${this._renderLayerList()}</calcite-flow-item><calcite-flow-item .heading=${this.selectedLayer?.title ?? void 0} .description=${this._messages.headings.totalFeatures.replace("{number}", this._featuresFromSelectedLayer.length.toString())} .selected=${!!this.selectedLayer} @calciteFlowItemBack=${() => this.selectedLayer = void 0}>${this._renderFeaturesList()}</calcite-flow-item></calcite-flow>`;
  }
  _renderGettingResults() {
    return r`<calcite-panel class="white-panel-background"><calcite-loader .label=${this._messages.gettingResults} .text=${this._messages.gettingResults}></calcite-loader></calcite-panel>`;
  }
  _renderLanding(e) {
    const { elements: t, globalFunctionResults: a, aggregatedGeometry: s } = e;
    return r`<calcite-panel class="white-panel-background">${this._renderTraceResultsHeading()}${s != null ? this._renderAggregatedGeometry(s) : null}${s != null && !t.length ? this._renderNoSelectableResults() : null}${t.length > 0 ? this.hideFeatureResults ? this._renderFeaturesAreHidden() : this._renderElementsResults() : null}${a.length > 0 ? this._renderFunctionsResults(a) : null}</calcite-panel>`;
  }
  _renderAggregatedGeometry(e) {
    return r`<div class="aggregated-geometry-container"><arcgis-utility-network-aggregated-geometry .graphicsColor=${this.aggregatedGeometryGraphicsColor} .geometry=${e} .view=${this.view} @arcgisHideGraphicsChange=${this._handleHideGraphicsChange} auto-destroy-disabled ${g(this._aggregateGeometryRefChange)}></arcgis-utility-network-aggregated-geometry><calcite-swatch id=geometry-color-swatch .label=${this._messages.labels.aggregatedGeometryGraphicsColor} .color=${this.aggregatedGeometryGraphicsColor.toCss()} .disabled=${this._aggregatedGeometryDisabled}></calcite-swatch><calcite-popover .heading=${this._messages.headings.setColor} .label=${this._messages.headings.setColor} reference-element=geometry-color-swatch closable ${g(this._popoverRef)}><calcite-color-picker alpha-channel channels-disabled clearable hex-disabled saved-disabled .value=${this.aggregatedGeometryGraphicsColor} @calciteColorPickerChange=${(t) => {
      const a = t.target.value;
      this.arcgisAggregatedGeometryGraphicsColorChange.emit(a);
    }} .disabled=${this._aggregatedGeometryDisabled}></calcite-color-picker></calcite-popover></div>`;
  }
  _renderFeaturesAreHiddenLanding() {
    return r`<calcite-panel class="white-panel-background">${this._renderTraceResultsHeading()}${this._renderFeaturesAreHidden()}</calcite-panel>`;
  }
  _renderFeaturesAreHidden() {
    return r`<div class="no-selectable-results">${this._messages.resultFeaturesAreHidden}</div>`;
  }
  _renderNoSelectableResults() {
    return r`<div class="no-selectable-results">${this._messages.noSelectableFeatures}</div>`;
  }
  _renderElementsResults() {
    return r`<calcite-list .label=${this._messages.headings.traceResultsGeneric}><calcite-list-item id=elements-list-item .label=${this._messages.headings.features} @calciteListItemSelect=${() => this.isElementsSelected = !0}><calcite-chip .label=${this._messages.labels.numFeatures} scale=s slot=content-end>${this.numResults}</calcite-chip><calcite-icon icon=chevron-right slot=content-end></calcite-icon></calcite-list-item></calcite-list>`;
  }
  _renderFunctionsResults(e) {
    return r`<div class="functions-heading">${this._messages.headings.functions}</div><calcite-table .caption=${this._messages.labels.functionResults}>${e.filter((t) => t.networkAttributeName != null && t.result != null).map((t) => r`<calcite-table-row><calcite-table-cell>${t.networkAttributeName}</calcite-table-cell><calcite-table-cell>${t.result}</calcite-table-cell></calcite-table-row>`)}</calcite-table>`;
  }
  _renderLayerList() {
    const e = Array.from(this._layerIdToFeatures.entries()), t = Array.from(this._subtypeCodeToFeatures.entries()), s = e.concat(t).sort(this._compareByLayerTitle).map(this._renderLayerListItem);
    return this._elementsWithoutLayer.length > 0 && s.push(this._renderUnknownListItem()), r`<calcite-list .label=${this._messages.labels.traceResultElementsByLayer} .loading=${this.state === "loading"}>${s}</calcite-list>`;
  }
  _renderUnknownListItem() {
    return r`<calcite-list-item .label=${this._messages.unknown} disabled><calcite-chip .label=${this._messages.labels.numElements} slot=content-end scale=s>${this._elementsWithoutLayer.length}</calcite-chip></calcite-list-item>`;
  }
  _renderFeaturesList() {
    return r`<calcite-list .label=${this._messages.headings.traceResultsGeneric}>${this._featuresFromSelectedLayer.map(this._renderFeatureListItem)}</calcite-list>`;
  }
  _renderTraceResultsHeading() {
    return r`<div class="results-heading"><div class="results-heading-title">${this._messages.headings.traceResultsGeneric}</div>${this.traceConfigTitle ? r`<div class="results-heading-subtitle">${this.traceConfigTitle}</div>` : null}</div>`;
  }
  _renderErrorLanding(e) {
    let t = e.message;
    switch (e.details?.raw?.extendedCode) {
      case p.dirtyAreasDiscovered:
        t = this._messages.traceErrors.dirtyAreasDiscovered;
        break;
      case p.noValidControllers:
        t = this._messages.traceErrors.noValidControllers;
        break;
    }
    return r`<calcite-panel class="white-panel-background">${this._renderTraceResultsHeading()}<div class="no-results-landing"><calcite-icon icon=exclamation-mark-triangle scale=l></calcite-icon><div class="no-results-heading">${this._messages.traceFailedHeading}</div><div class="no-results-description">${this._messages.traceFailedDescription}</div><div class="no-results-description">${t}</div></div></calcite-panel>`;
  }
  _renderNoResultsLanding() {
    return r`<calcite-panel class="white-panel-background">${this._renderTraceResultsHeading()}<div class="no-results-landing"><calcite-icon icon=exclamation-mark-triangle scale=l></calcite-icon><div class="no-results-heading">${this._messages.noResultsHeading}</div><div class="no-results-description">${this._messages.noResultsDescription}</div></div></calcite-panel>`;
  }
  _renderNoTraceLanding() {
    return r`<calcite-panel class="white-panel-background">${this._renderTraceResultsHeading()}<div class="no-results-landing"><calcite-icon icon=utility-network-trace scale=l></calcite-icon><div class="no-results-heading">${this._messages.noTraceConfigHeading}</div><div class="no-results-description">${this._messages.noTraceConfigDescription}</div></div></calcite-panel>`;
  }
}
f("arcgis-utility-network-trace-results", E);
export {
  E as ArcgisUtilityNetworkTraceResults
};
