/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
import { c as m } from "../../chunks/runtime.js";
import { css as y, html as s } from "lit";
import { ref as g } from "lit/directives/ref.js";
import { keyed as u } from "lit/directives/keyed.js";
import d from "@arcgis/core/Color.js";
import "@arcgis/core/core/Error.js";
import { when as f } from "@arcgis/core/core/reactiveUtils.js";
import b from "@arcgis/core/networks/UtilityNetworkTraceAnalysis.js";
import { LitElement as w, createEvent as l } from "@arcgis/lumina";
import { log as T } from "@arcgis/toolkit/log";
import { u as _ } from "../../chunks/useT9n.js";
import { m as v } from "../../chunks/useViewModel.js";
import { l as R } from "../../chunks/async-utils.js";
const $ = y`:host{--arcgis-internal-color-black-30: color-mix(in srgb, #000000 30.2%, transparent);--arcgis-internal-box-shadow: var(--calcite-spacing-none) var(--calcite-spacing-px) var(--calcite-spacing-base) var(--arcgis-internal-color-black-30);--arcgis-internal-top-max-width: calc(min(100cqw, 100vw) - var(--calcite-spacing-xxxl));--arcgis-internal-panel-width: 300px;--arcgis-internal-panel-height: 100%;--arcgis-internal-panel-height-sm: 240px;--arcgis-internal-panel-height-md: 420px;--arcgis-internal-panel-height-lg: 540px;--arcgis-internal-panel-height-xl: 680px;--arcgis-internal-panel-gap: var(--calcite-spacing-lg);--arcgis-internal-panel-actions-gap: var(--calcite-spacing-sm);--arcgis-internal-basemap-gallery-width-lg: 450px;--arcgis-internal-collapse-icon-flip: scaleX(1);--arcgis-internal-row-direction: row;--arcgis-internal-legend-width: 300px;--arcgis-internal-layout-overlay-space-top: var(--arcgis-layout-overlay-space-top, 0px);--arcgis-internal-layout-overlay-space-bottom: var(--arcgis-layout-overlay-space-bottom, 0px);--arcgis-internal-layout-overlay-space-left: var(--arcgis-layout-overlay-space-left, 0px);--arcgis-internal-layout-overlay-space-right: var(--arcgis-layout-overlay-space-right, 0px);--arcgis-internal-view-color-focus: var(--arcgis-view-color-focus, var(--calcite-color-brand));--arcgis-internal-attribution-space-bottom: var(--arcgis-internal-layout-overlay-space-bottom);--arcgis-internal-attribution-space-left: var(--arcgis-internal-layout-overlay-space-left);--arcgis-internal-attribution-space-right: var(--arcgis-internal-layout-overlay-space-right);--arcgis-internal-attribution-font-size: var(--calcite-font-size-sm);--arcgis-internal-attribution-font-size-sm: var(--calcite-font-size-xs);--arcgis-internal-sketch-justify-content: flex-start}:host{display:flex;flex-direction:column;height:var(--arcgis-internal-panel-height, 100%)}.inputs-tab-container{display:flex;flex-direction:column;height:100%}.trace-inputs-warning{flex:none;height:fit-content;--calcite-panel-background-color: var(--calcite-color-foreground-1);calcite-notice{margin:var(--calcite-spacing-md) var(--calcite-spacing-md) 0 var(--calcite-spacing-md)}}arcgis-utility-network-trace-inputs[mode=default]{height:auto}calcite-tabs{display:flex;flex-direction:column;height:100%}calcite-tab{--calcite-tab-content-space-y: 0;min-height:var(--arcgis-internal-panel-height-sm, 240px)}calcite-tab:not([selected]){flex:0}calcite-panel{--calcite-panel-background-color: var(--calcite-color-foreground-1)}calcite-notice{margin:var(--calcite-spacing-md)}`, C = v(b);
class E extends w {
  constructor() {
    super(...arguments), this._messages = _({ blocking: !0 }), this._viewModel = C(this), this._highlightHandles = [], this._handleRunTraceButtonClick = () => {
      this._setTraceWarnings(), !(this.showNoStartingPointsWarning || this.showMissingTerminalWarning) && (this.showNoStartingPointsWarning = !1, this.showMissingTerminalWarning = !1, this._clearTraceResult(), this._switchTab("results"), this._runTrace());
    }, this._handleTraceInputsRefChange = (e) => {
      e && (this._traceInputsElement = e);
    }, this._handleTraceResultsRefChange = (e) => {
      e && (this._traceResultsElement = e);
    }, this.activeTab = "input", this.showMissingTerminalWarning = !1, this.showNoStartingPointsWarning = !1, this.mode = "default", this.autoDestroyDisabled = !1, this.aggregatedGeometryGraphicsColor = new d([255, 255, 0, 0.6]), this.disableHighlightFeatureResults = !1, this.hideActionBar = !1, this.hideFeatureResults = !1, this.state = this._viewModel.state, this.view = this._viewModel.view, this.arcgisHideGraphicsChange = l(), this.arcgisReady = l(), this.arcgisTraceLocationSelectEnd = l(), this.arcgisTraceLocationSelectStart = l(), this.arcgisTraceResultClear = l(), this.arcgisTraceResultFeaturesReady = l();
  }
  static {
    this.properties = { activeTab: 16, traceError: 16, traceResult: 16, showMissingTerminalWarning: 16, showNoStartingPointsWarning: 16, mode: 16, autoDestroyDisabled: 5, beforeTraceLocationSelectStart: 0, aggregatedGeometryGraphicsColor: 0, disableHighlightFeatureResults: 5, hideActionBar: 5, hideFeatureResults: 5, label: 3, messageOverrides: 0, traceResultFeatures: 32, referenceElement: 1, state: 32, view: 0 };
  }
  static {
    this.styles = $;
  }
  get _allLayers() {
    const { view: e } = this;
    return e?.map ? e.map.allLayers.toArray().concat(e.map.allTables.toArray()) : [];
  }
  get traceResultFeatures() {
    return this._traceResultsElement?.traceResultFeatures ?? [];
  }
  async destroy() {
    this._clearHighlights(), this._traceResultsElement?.destroy(), this._traceInputsElement?.destroy(), await this.manager.destroy();
  }
  load() {
    this.manager.onLifecycle(() => [
      f(() => !this._viewModel.utilityNetwork, () => this._switchTab("input"))
    ]);
  }
  _clearTraceResult() {
    this.traceResult = void 0, this._clearHighlights(), this._clearAggregatedGeometryGraphics();
  }
  _setTraceWarnings() {
    if (!this._traceInputsElement)
      return;
    const { traceLocations: e, traceLocationFlagInfos: t, unTraceConfiguration: a, isSubnetworkNameTraceSelected: i } = this._traceInputsElement, r = !!a?.subnetworkName, c = e?.some((n) => n.type === "starting-point"), o = t?.some((n) => !!n.flagProperties.terminalConfiguration && !n.flagProperties.selectedTerminals?.size) ?? !1;
    this.traceError = void 0, this.showNoStartingPointsWarning = !i && !c || i && !r, this.showMissingTerminalWarning = o;
  }
  _switchTab(e) {
    this.activeTab = e;
  }
  _getLoadError(e) {
    const { _messages: t } = this;
    switch (e) {
      case "no-user-type-extension":
        return t.errors.loadErrors.noUserTypeExtension;
      case "no-utility-network":
        return t.errors.loadErrors.noUtilityNetwork;
      case "no-view":
        return t.errors.loadErrors.noView;
      case "sceneView-not-supported":
        return t.errors.loadErrors.sceneViewNotSupported;
      default:
        return e;
    }
  }
  _clearHighlights() {
    this._highlightHandles.forEach((e) => e.remove()), this._highlightHandles = [];
  }
  _clearAggregatedGeometryGraphics() {
    this._traceResultsElement?.clearAggregatedGeometryGraphics();
  }
  _highlightResults() {
    const { traceResult: e, view: t } = this, a = this._viewModel.utilityNetwork;
    if (!a || !e?.elements || !t)
      return;
    a.getObjectIdsFromElements(e.elements).forEach((r) => {
      const c = t.allLayerViews.find((n) => {
        const h = n.layer;
        if (a.isUtilityLayer(h)) {
          const p = Number(r.layerUrl.split("/").pop());
          return h.layerId === p;
        }
        return !1;
      });
      if (!c)
        return;
      const o = c.highlight(r.objectIds);
      this._highlightHandles.push(o);
    });
  }
  async _runTrace() {
    const e = this._traceInputsElement?.selectedNamedTraceConfiguration, t = this._traceInputsElement?.unTraceConfiguration;
    if (!(e?.traceType && t)) {
      T("error", this, "Trace configuration not found");
      return;
    }
    const a = this._traceInputsElement?.traceLocations;
    try {
      this.traceResult = await this._viewModel.executeTraceConfiguration({
        traceType: e.traceType,
        traceConfiguration: t,
        traceLocations: a ?? [],
        resultTypes: e.resultTypes,
        outSpatialReference: this.view?.spatialReference
      }), this.disableHighlightFeatureResults || this._highlightResults();
    } catch (i) {
      R(i, this, "Error while running trace"), this.traceError = i, this.traceResult = void 0;
    }
  }
  _handleHideGraphicsChange(e) {
    e.stopPropagation(), this.arcgisHideGraphicsChange.emit(e.detail);
  }
  _handleTraceLocationSelectStart(e) {
    e.stopPropagation(), this.arcgisTraceLocationSelectStart.emit(e.detail).defaultPrevented && e.preventDefault();
  }
  _handleTraceLocationSelectEnd(e) {
    e.stopPropagation(), this.arcgisTraceLocationSelectEnd.emit();
  }
  _handleTraceResultFeaturesReady(e) {
    e.stopPropagation(), this.arcgisTraceResultFeaturesReady.emit();
  }
  _handleAggregatedGeometryGraphicsColorChange(e) {
    const t = e.detail;
    this.aggregatedGeometryGraphicsColor = new d(t);
  }
  _handleSelectedNamedTraceConfigurationChange() {
    this.showNoStartingPointsWarning = !1, this.showMissingTerminalWarning = !1;
  }
  _handleUtilityNetworkChange() {
    this._viewModel.utilityNetwork = this._traceInputsElement?.selectedUtilityNetwork;
  }
  renderMissingTerminalWarning() {
    return s`<calcite-panel class="trace-inputs-warning"><calcite-notice open icon=exclamation-mark-triangle closable kind=danger scale=s @calciteNoticeClose=${() => this.showMissingTerminalWarning = !1}><div slot=title>${this._messages.errors.missingTerminalTitle}</div><div slot=message>${this._messages.errors.missingTerminalBody}</div></calcite-notice></calcite-panel>`;
  }
  renderNoStartingPointsWarning() {
    return s`<calcite-panel class="trace-inputs-warning"><calcite-notice open icon=exclamation-mark-triangle closable kind=danger scale=s @calciteNoticeClose=${() => this.showNoStartingPointsWarning = !1}><div slot=title>${this._messages.errors.noStartingPointsTitle}</div><div slot=message>${this._messages.errors.noStartingPointsBody}</div></calcite-notice></calcite-panel>`;
  }
  renderResultsTab() {
    return u(`${this.el.id}__results-tab-item`, s`<calcite-tab .selected=${this.activeTab === "results"}>${this.state === "executing" ? s`<calcite-panel><calcite-loader .label=${this._messages.runningTrace} .text=${this._messages.runningTrace}></calcite-loader></calcite-panel>` : s`<arcgis-utility-network-trace-results .autoDestroyDisabled=${this.autoDestroyDisabled} .aggregatedGeometryGraphicsColor=${this.aggregatedGeometryGraphicsColor} .hideActionBar=${this.hideActionBar} .hideFeatureResults=${this.hideFeatureResults} .layers=${this._allLayers} .messageOverrides=${{ resultFeaturesAreHidden: this.messageOverrides?.resultFeaturesAreHidden }} .referenceElement=${this.referenceElement} .traceConfigTitle=${this._selectedTraceConfig?.title} .traceError=${this.traceError} .traceResult=${this.traceResult} .utilityNetwork=${this._viewModel.utilityNetwork ?? void 0} .view=${this.view ?? void 0} @arcgisAggregatedGeometryGraphicsColorChange=${this._handleAggregatedGeometryGraphicsColorChange} @arcgisHideGraphicsChange=${this._handleHideGraphicsChange} @arcgisTraceResultFeaturesReady=${this._handleTraceResultFeaturesReady} ${g(this._handleTraceResultsRefChange)}></arcgis-utility-network-trace-results>`}</calcite-tab>`);
  }
  renderResultsFooter() {
    const { traceResult: e } = this, a = !!(e?.elements.length || e?.globalFunctionResults.length || e?.aggregatedGeometry) && this._traceResultsElement?.state === "ready", i = this._traceResultsElement?.numResults ?? 0;
    return s`<calcite-button appearance=outline width=full @click=${() => {
      this._switchTab("input"), this._clearTraceResult(), this.arcgisTraceResultClear.emit();
    }} .disabled=${!a} slot=footer>${i > 0 && !this.hideFeatureResults && this.state !== "executing" ? this._messages.buttons.clearResultsCustom.replace("{number}", i.toString()) : this._messages.buttons.clearResultsGeneric}</calcite-button>`;
  }
  renderInputTab() {
    const { mode: e } = this, { loadError: t } = this._viewModel, i = (t === "no-user-type-extension" || t === "sceneView-not-supported" ? s`<calcite-notice kind=danger open scale=s slot=content-top width=auto><div slot=message>${this._getLoadError(t)}</div></calcite-notice>` : void 0) ?? s`${this.showNoStartingPointsWarning && e === "default" && this.renderNoStartingPointsWarning() || ""}${this.showMissingTerminalWarning && e === "default" && this.renderMissingTerminalWarning() || ""}<arcgis-utility-network-trace-inputs .autoDestroyDisabled=${this.autoDestroyDisabled} .hideActionBar=${this.hideActionBar} .referenceElement=${this.referenceElement} .view=${this.view ?? void 0} .beforeTraceLocationSelectStart=${this.beforeTraceLocationSelectStart} @arcgisPropertyChange=${(r) => {
      r.stopPropagation(), r.detail.name === "mode" && (this.mode = r.target.mode);
    }} @arcgisSelectedNamedTraceConfigurationChange=${this._handleSelectedNamedTraceConfigurationChange} @arcgisTraceLocationSelectEnd=${this._handleTraceLocationSelectEnd} @arcgisTraceLocationSelectStart=${this._handleTraceLocationSelectStart} @arcgisUtilityNetworkChange=${this._handleUtilityNetworkChange} ${g(this._handleTraceInputsRefChange)}></arcgis-utility-network-trace-inputs>`;
    return u(`${this.el.id}__inputs-tab-item`, s`<calcite-tab .selected=${this.activeTab === "input"}><div class="inputs-tab-container">${i}</div></calcite-tab>`);
  }
  renderInputFooter() {
    const { mode: e, state: t } = this;
    if (e !== "default")
      return null;
    const a = t === "disabled" || t === "loading" || !this._traceInputsElement?.unTraceConfiguration;
    return s`<calcite-button appearance=solid width=full @click=${this._handleRunTraceButtonClick} slot=footer .disabled=${a}>${this._messages.buttons.getResults}</calcite-button>`;
  }
  render() {
    const { activeTab: e, state: t } = this;
    return s`<calcite-panel><calcite-tabs layout=center position=top><calcite-tab-nav slot=title-group><calcite-tab-title @click=${() => this._switchTab("input")} .selected=${e === "input"}>${this._messages.tabs.inputTab}</calcite-tab-title><calcite-tab-title @click=${() => this._switchTab("results")} .selected=${e === "results"} .disabled=${t === "disabled" || t === "loading"}>${this._messages.tabs.resultsTab}</calcite-tab-title></calcite-tab-nav>${this.renderInputTab()}${t === "ready" || t === "executing" ? this.renderResultsTab() : null}</calcite-tabs>${e === "input" ? this.renderInputFooter() : null}${e === "results" ? this.renderResultsFooter() : null}</calcite-panel>`;
  }
}
m("arcgis-utility-network-trace-analysis", E);
export {
  E as ArcgisUtilityNetworkTraceAnalysis
};
