/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
import { c as p } from "../../chunks/runtime.js";
import y from "@arcgis/core/Color.js";
import "@arcgis/core/core/Error.js";
import "@arcgis/core/Graphic.js";
import { LitElement as f, createEvent as o } from "@arcgis/lumina";
import { log as d, composeMissingPropertyMessage as h, composeEmptyPropertyMessage as _ } from "@arcgis/toolkit/log";
import { css as v, html as l } from "lit";
import { createRef as b, ref as u } from "lit/directives/ref.js";
import { u as R } from "../../chunks/useT9n.js";
import { l as C } from "../../chunks/async-utils.js";
import { q as w, c as $ } from "../../chunks/layer-utils.js";
const E = v`:host{min-height:var(--arcgis-internal-panel-height-sm, 240px);height:100%}arcgis-features{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)}`, g = {
  dirtyAreasDiscovered: -2147208511,
  noValidControllers: -2147208935,
  pathNotFound: -2147208444
};
class F extends f {
  constructor() {
    super(...arguments), this._defaultPopupTemplateEnabled = !0, this._messages = R({ blocking: !0 }), this._elementsWithoutLayer = [], this._popoverRef = b(), this._layerIdToFeatures = /* @__PURE__ */ new Map(), this._layerIdToLayer = /* @__PURE__ */ new Map(), this._subtypeCodeToFeatures = /* @__PURE__ */ new Map(), this._sourceIdToElements = /* @__PURE__ */ new Map(), this._unLayers = [], this._queryFeaturesOnLayer = async ([e, t]) => {
      const a = this.utilityNetwork?.getLayerIdBySourceId(e), s = this._getLayerByLayerId(a), r = this._getElementsUniqueByGlobalId(t);
      if (a == null || !s) {
        this._elementsWithoutLayer.push(...r);
        return;
      }
      const i = s.createQuery();
      i.gdbVersion = this.utilityNetwork?.gdbVersion, i.objectIds = r.map((c) => c.objectId), i.outFields = ["*"];
      const { features: n } = await w(s, i);
      n.forEach((c) => {
        const m = c.layer;
        c.getEffectivePopupTemplate(this._defaultPopupTemplateEnabled) || (c.popupTemplate = m.createPopupTemplate());
      }), $(s) ? n.forEach((c) => this._addOrCreateMapValue(this._subtypeCodeToFeatures, c.layer.subtypeCode, c)) : this._layerIdToFeatures.set(a, n);
    }, this._aggregateGeometryRefChange = (e) => {
      e && (this._aggregatedGeometryComponentElement = e);
    }, this._featuresRefChange = (e) => {
      e && (this._featuresComponentElement = e);
    }, this._aggregatedGeometryDisabled = !1, this.aggregatedGeometryGraphicsColor = new y([255, 255, 0, 0.6]), this.hideActionBar = !1, this.hideFeatureResults = !1, this.featuresFromSelectedLayer = [], this.isElementsSelected = !1, this.layers = [], this.state = "ready", this.traceResultFeatures = [], this.autoDestroyDisabled = !1, this.arcgisAggregatedGeometryGraphicsColorChange = o(), this.arcgisHideGraphicsChange = o(), this.arcgisSelectedLayerChange = o(), this.arcgisSelectedResultTypeChange = o(), this.arcgisTraceResultFeaturesReady = o();
  }
  static {
    this.properties = { _aggregatedGeometryDisabled: 16, _featuresComponentElement: 16, aggregatedGeometryGraphicsColor: 0, hideActionBar: 5, hideFeatureResults: 5, featuresFromSelectedLayer: 0, isElementsSelected: 5, layers: 0, messageOverrides: 0, numResults: 32, referenceElement: 1, selectedLayer: 0, state: 1, traceConfigTitle: 1, traceError: 0, traceResult: 0, traceResultFeatures: 0, utilityNetwork: 0, view: 0, autoDestroyDisabled: 5 };
  }
  static {
    this.styles = 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 || d("warn", this, h("utilityNetwork")), this.layers.length === 0 && d("warn", this, _("layers")), this.view || d("warn", this, h("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((r) => "layerId" in r && r.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;
    try {
      t.loaded || (this.state = "loading", await t.load());
    } catch (r) {
      C(r, this, "Error while loading the selected utility network");
    }
    this._unLayers = e.filter((r) => t.isUtilityLayer(r));
    const s = this._unLayers.filter((r) => !r.loaded).map((r) => r.load());
    s.length > 0 && (this.state = "loading", (await Promise.allSettled(s)).forEach((i) => {
      i.status === "rejected" && d("error", this, `Failed to load layer. Reason: ${i.reason}`);
    }));
  }
  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((i, n) => {
      if (i.status === "rejected") {
        const [c] = e[n];
        d("error", this, `Failed to query features for source ${c}. Reason: ${i.reason}`);
      }
    });
    const s = Array.from(this._layerIdToFeatures.values()), r = Array.from(this._subtypeCodeToFeatures.values());
    this.traceResultFeatures = s.concat(r).flat();
  }
  _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: r } = t, i = !a.length && !s.length && !r, n = a.length > 0 && !s.length && !r;
    return i ? this._renderNoResultsLanding() : this.state === "loading" ? this._renderGettingResults() : this.hideFeatureResults && n ? this._renderFeaturesAreHidden() : this.isElementsSelected || n ? l`<arcgis-features-next .autoDestroyDisabled=${this.autoDestroyDisabled} .defaultPopupTemplateEnabled=${this._defaultPopupTemplateEnabled} .features=${this.traceResultFeatures} .hideActionBar=${this.hideActionBar} .hideCloseButton=${n} hide-select-feature initial-display-mode=list @arcgisClose=${() => this.isElementsSelected = !1} open .referenceElement=${this.referenceElement} .view=${this.view} ${u(this._featuresRefChange)}></arcgis-features-next>` : this._renderLanding(t);
  }
  _renderGettingResults() {
    return l`<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 l`<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 l`<div class="aggregated-geometry-container"><arcgis-utility-network-aggregated-geometry .graphicsColor=${this.aggregatedGeometryGraphicsColor} .geometry=${e} .view=${this.view} @arcgisHideGraphicsChange=${this._handleHideGraphicsChange} auto-destroy-disabled ${u(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 ${u(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>`;
  }
  _renderFeaturesAreHidden() {
    return l`<div class="no-selectable-results">${this._messages.resultFeaturesAreHidden}</div>`;
  }
  _renderNoSelectableResults() {
    return l`<div class="no-selectable-results">${this._messages.noSelectableFeatures}</div>`;
  }
  _renderElementsResults() {
    return l`<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 l`<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 && t.functionType != null).map((t) => {
      const { functionName: a, networkAttributeName: s, functionType: r, result: i } = t, n = a || `${s} ${r}`;
      return l`<calcite-table-row><calcite-table-cell>${n}</calcite-table-cell><calcite-table-cell>${i}</calcite-table-cell></calcite-table-row>`;
    })}</calcite-table>`;
  }
  _renderTraceResultsHeading() {
    return l`<div class="results-heading"><div class="results-heading-title">${this._messages.headings.traceResultsGeneric}</div>${this.traceConfigTitle ? l`<div class="results-heading-subtitle">${this.traceConfigTitle}</div>` : null}</div>`;
  }
  _renderErrorLanding(e) {
    let t = e.message;
    switch (e.details?.raw?.extendedCode) {
      case g.dirtyAreasDiscovered:
        t = this._messages.traceErrors.dirtyAreasDiscovered;
        break;
      case g.noValidControllers:
        t = this._messages.traceErrors.noValidControllers;
        break;
      case g.pathNotFound:
        t = this._messages.traceErrors.pathNotFound;
        break;
    }
    return l`<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 l`<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 l`<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>`;
  }
}
p("arcgis-utility-network-trace-results", F);
export {
  F as ArcgisUtilityNetworkTraceResults
};
