/* COPYRIGHT Esri - https://js.arcgis.com/5.0/LICENSE.txt */
import { c as y } from "../../chunks/runtime.js";
import { css as f, html as r } from "lit";
import { ref as o } from "lit/directives/ref.js";
import { keyed as h } from "lit/directives/keyed.js";
import g from "@arcgis/core/Color.js";
import "@arcgis/core/core/Error.js";
import b from "@arcgis/core/networks/UtilityNetworkTraceAnalysis.js";
import { LitElement as v, createEvent as l } from "@arcgis/lumina";
import { log as u } from "@arcgis/toolkit/log";
import { u as w } from "../../chunks/useT9n.js";
import { m as _ } from "../../chunks/useViewModel.js";
const T = f`: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%}#no-starting-points-panel{flex:none;height:fit-content;--calcite-panel-background-color: var(--calcite-color-foreground-1)}#no-starting-points-notice{margin:var(--calcite-spacing-md) var(--calcite-spacing-md) 0 var(--calcite-spacing-md)}calcite-tabs{display:flex;flex-direction:column;height:100%}calcite-tab{--calcite-tab-content-space-y: 0}calcite-tab:not([selected]){flex:0}calcite-panel{--calcite-panel-background-color: var(--calcite-color-foreground-1)}calcite-notice{margin:var(--calcite-spacing-md)}`, R = _(b);
class $ extends v {
  constructor() {
    super(...arguments), this._messages = w({ blocking: !0 }), this._viewModel = R(this), this._highlightHandles = [], this._handleRunTraceButtonClick = () => {
      const t = this._traceInputsElement?.traceLocations?.some((a) => a.type === "starting-point");
      if (this.traceError = void 0, !this._isSubnetworkNameTraceSelected && !t) {
        this.showNoStartingPointsWarning = !0;
        return;
      }
      this.showNoStartingPointsWarning = !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.showNoStartingPointsWarning = !1, this.mode = "default", this.autoDestroyDisabled = !1, this.aggregatedGeometryGraphicsColor = new g([255, 255, 0, 0.6]), this.disableHighlightFeatureResults = !1, this.hideFeatureResults = !1, this.state = this._viewModel.state, this.view = this._viewModel.view, this.arcgisHideGraphicsChange = l(), this.arcgisTraceLocationSelectStart = l(), this.arcgisTraceLocationSelectEnd = l(), this.arcgisTraceResultFeaturesReady = l(), this.arcgisTraceResultClear = l(), this.arcgisReady = l();
  }
  static {
    this.properties = { activeTab: 16, traceError: 16, traceResult: 16, showNoStartingPointsWarning: 16, mode: 16, autoDestroyDisabled: 5, beforeTraceLocationSelectStart: 0, aggregatedGeometryGraphicsColor: 0, disableHighlightFeatureResults: 5, hideFeatureResults: 5, label: 3, messageOverrides: 0, traceResultFeatures: 32, referenceElement: 1, state: 32, view: 0 };
  }
  static {
    this.styles = T;
  }
  get _allLayers() {
    const { view: e } = this;
    return e?.map ? e.map.allLayers.toArray().concat(e.map.allTables.toArray()) : [];
  }
  get _isSubnetworkNameTraceSelected() {
    const e = this._traceInputsElement?.selectedNamedTraceConfiguration?.traceType;
    return !!this._traceInputsElement?.selectedNamedTraceConfiguration?.traceConfiguration?.subnetworkName && e === "subnetwork";
  }
  get traceResultFeatures() {
    return this._traceResultsElement?.traceResultFeatures ?? [];
  }
  async destroy() {
    this._clearHighlights(), this._traceResultsElement?.destroy(), this._traceInputsElement?.destroy(), await this.manager.destroy();
  }
  _clearTraceResult() {
    this.traceResult = void 0, this._clearHighlights(), this._clearAggregatedGeometryGraphics();
  }
  _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((i) => {
      const s = t.allLayerViews.find((p) => {
        const c = p.layer;
        if (a.isUtilityLayer(c)) {
          const m = Number(i.layerUrl.split("/").pop());
          return c.layerId === m;
        }
        return !1;
      });
      if (!s)
        return;
      const d = s.highlight(i.objectIds);
      this._highlightHandles.push(d);
    });
  }
  async _runTrace() {
    const e = this._traceInputsElement?.selectedNamedTraceConfiguration, t = this._traceInputsElement?.unTraceConfiguration;
    if (!(e?.traceType && t)) {
      u("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 (n) {
      const i = n, s = i.details ? { detail: i.details } : void 0;
      u("error", this, `Error while running trace: ${String(i)}`, s), 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 g(t);
  }
  _handleTraceInputsChange() {
  }
  _handleSelectedNamedTraceConfigurationChange() {
    this.showNoStartingPointsWarning = !1;
  }
  _handleUtilityNetworkChange() {
    this._viewModel.utilityNetwork = this._traceInputsElement?.selectedUtilityNetwork;
  }
  renderNoStartingPointsWarning() {
    return r`<calcite-panel id=no-starting-points-panel><calcite-notice id=no-starting-points-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 h(`${this.el.id}__results-tab-item`, r`<calcite-tab .selected=${this.activeTab === "results"}>${this._viewModel.state === "executing" ? r`<calcite-panel><calcite-loader .label=${this._messages.runningTrace} .text=${this._messages.runningTrace}></calcite-loader></calcite-panel>` : r`<arcgis-utility-network-trace-results .aggregatedGeometryGraphicsColor=${this.aggregatedGeometryGraphicsColor} .hideFeatureResults=${this.hideFeatureResults} .referenceElement=${this.referenceElement} .layers=${this._allLayers} .traceConfigTitle=${this._selectedTraceConfig?.title} .traceError=${this.traceError} .traceResult=${this.traceResult} .utilityNetwork=${this._viewModel.utilityNetwork ?? void 0} .view=${this.view ?? void 0} .messageOverrides=${{ resultFeaturesAreHidden: this.messageOverrides?.resultFeaturesAreHidden }} @arcgisHideGraphicsChange=${this._handleHideGraphicsChange} @arcgisTraceResultFeaturesReady=${this._handleTraceResultFeaturesReady} @arcgisAggregatedGeometryGraphicsColorChange=${this._handleAggregatedGeometryGraphicsColorChange} .autoDestroyDisabled=${this.autoDestroyDisabled} ${o(this._handleTraceResultsRefChange)}></arcgis-utility-network-trace-results>`}</calcite-tab>`);
  }
  renderResultsFooter() {
    const { mode: e, state: t } = this;
    if (e !== "default")
      return null;
    const { traceResult: a } = this, i = !!(a?.elements.length || a?.globalFunctionResults.length || a?.aggregatedGeometry) && this._traceResultsElement?.state === "ready", s = this._traceResultsElement?.numResults ?? 0;
    return r`<calcite-button appearance=outline width=full @click=${() => {
      this._switchTab("input"), this._clearTraceResult(), this.arcgisTraceResultClear.emit();
    }} .disabled=${!i} slot=footer>${s > 0 && !this.hideFeatureResults && t !== "executing" ? this._messages.buttons.clearResultsCustom.replace("{number}", s.toString()) : this._messages.buttons.clearResultsGeneric}</calcite-button>`;
  }
  renderInputTab() {
    return h(`${this.el.id}__inputs-tab-item`, r`<calcite-tab .selected=${this.activeTab === "input"}><div class="inputs-tab-container">${this.showNoStartingPointsWarning && this.mode === "default" ? this.renderNoStartingPointsWarning() : null}<arcgis-utility-network-trace-inputs .view=${this.view || void 0} .referenceElement=${this.referenceElement} .beforeTraceLocationSelectStart=${this.beforeTraceLocationSelectStart} @arcgisTraceInputsChange=${this._handleTraceInputsChange} @arcgisSelectedNamedTraceConfigurationChange=${this._handleSelectedNamedTraceConfigurationChange} @arcgisUtilityNetworkChange=${this._handleUtilityNetworkChange} @arcgisTraceLocationSelectStart=${this._handleTraceLocationSelectStart} @arcgisTraceLocationSelectEnd=${this._handleTraceLocationSelectEnd} @arcgisPropertyChange=${(e) => {
      e.stopPropagation(), e.detail.name === "mode" && (this.mode = e.target.mode);
    }} .autoDestroyDisabled=${this.autoDestroyDisabled} ${o(this._handleTraceInputsRefChange)}></arcgis-utility-network-trace-inputs></div></calcite-tab>`);
  }
  renderInputFooter() {
    const { mode: e, _viewModel: { state: t } } = this;
    return e !== "default" ? null : r`<calcite-button appearance=solid width=full @click=${this._handleRunTraceButtonClick} slot=footer .disabled=${t === "disabled"}>${this._messages.buttons.getResults}</calcite-button>`;
  }
  render() {
    const { _messages: e, _viewModel: { loadError: t, state: a } } = this, n = a === "disabled" && t != null, i = n && t !== "no-utility-network" ? r`<calcite-notice kind=warning open scale=s slot=content-top width=full><div slot=message>${this._getLoadError(t)}</div></calcite-notice>` : void 0;
    return r`<calcite-panel .loading=${this.view === void 0}><calcite-tabs layout=center position=top><calcite-tab-nav slot=title-group><calcite-tab-title @click=${() => this._switchTab("input")} .selected=${this.activeTab === "input"}>${e.tabs.inputTab}</calcite-tab-title><calcite-tab-title @click=${() => this._switchTab("results")} .selected=${this.activeTab === "results"} .disabled=${n}>${e.tabs.resultsTab}</calcite-tab-title></calcite-tab-nav>${this.view ? this.renderInputTab() : null}${this.view && this._viewModel.utilityNetwork ? this.renderResultsTab() : null}</calcite-tabs>${i}${this.activeTab === "input" ? this.renderInputFooter() : null}${this.activeTab === "results" ? this.renderResultsFooter() : null}</calcite-panel>`;
  }
}
y("arcgis-utility-network-trace-analysis", $);
export {
  $ as ArcgisUtilityNetworkTraceAnalysis
};
