/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
import { c as k } from "../../chunks/runtime.js";
import { css as _, html as s } from "lit";
import { getOwningPortalUrl as N, hasUserTypeExtension as V } from "@arcgis/core/applications/Components/featureUtils.js";
import "@arcgis/core/core/Error.js";
import { on as b, watch as $ } from "@arcgis/core/core/reactiveUtils.js";
import T from "@arcgis/core/portal/Portal.js";
import "@arcgis/core/rest/networks/support/ValidateNetworkTopologyResult.js";
import { LitElement as A, createEvent as u, nothing as l } from "@arcgis/lumina";
import { log as d, composeMissingPropertyMessage as y } from "@arcgis/toolkit/log";
import { generateGuid as E } from "@arcgis/toolkit/string";
import { u as U } from "../../chunks/useT9n.js";
import { u as L } from "../../chunks/useView.js";
import { c as S, i as C, l as I, t as n } from "../../chunks/async-utils.js";
import { d as O } from "../../chunks/layer-utils.js";
const D = _`: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%)}calcite-block{margin:0;border-bottom:none}calcite-combobox{margin-bottom:var(--calcite-spacing-sm)}calcite-icon{width:32px}`, p = {
  noDirtyAreasInExtent: -2147208940,
  operationOnlyAllowedByOwner: -2147217144,
  cannotAcquireVersionLockV10: -2147217146,
  cannotAcquireVersionLockV11: -2147220947
};
class q extends A {
  constructor() {
    super(...arguments), this._messages = U({ blocking: !0 }), this._unVntGuid = `unvnt_${E()}`, this.disabled = !1, this.extentToValidate = "current", this.hideUtilityNetworkSelect = !1, this.state = { type: "disabled" }, this.view = L(this), this.arcgisReady = u(), this.arcgisValidateNetworkTopologyEnd = u(), this.arcgisValidateNetworkTopologyStart = u();
  }
  static {
    this.properties = { beforeValidateNetworkTopologyStart: 0, disabled: 5, extentToValidate: 1, hideUtilityNetworkSelect: 5, label: 1, messageOverrides: 0, referenceElement: 1, result: 0, state: 0, utilityNetwork: 0, view: 0 };
  }
  static {
    this.styles = D;
  }
  async loaded() {
    this.manager.onLifecycle(() => [
      b(() => this.view?.map?.allLayers, "change", (e) => {
        const t = e.added.concat(e.removed);
        this._getDirtyAreasLayer(t) && this._runSetup();
      }),
      b(() => this.view?.map?.utilityNetworks, "change", () => {
        this._runSetup();
      }),
      $(() => this.view, () => {
        this._runSetup();
      }, { initial: !0 })
    ]);
  }
  _getDirtyAreasLayer(e) {
    const t = this.utilityNetwork?.networkSystemLayers.dirtyAreasLayerUrl;
    if (t)
      return e.find((i) => O(i) && `${i.url}/${i.layerId}` === t);
  }
  async _handleValidateNetworkTopologyAction() {
    try {
      if (this.result = void 0, !this.view) {
        this.state = { type: "error-disable-component", message: this._messages.errors.noView };
        return;
      }
      if (!this.utilityNetwork) {
        this.state = { type: "error-disable-component", message: this._messages.errors.noUtilityNetworks };
        return;
      }
      this.beforeValidateNetworkTopologyStart && await this.beforeValidateNetworkTopologyStart();
      const { view: e, utilityNetwork: t } = this;
      if (!e) {
        this.state = { type: "error-disable-component", message: this._messages.errors.noView };
        return;
      }
      if (!t) {
        this.state = { type: "error-disable-component", message: this._messages.errors.noUtilityNetwork }, d("warn", this, y("utilityNetwork"));
        return;
      }
      if (this.arcgisValidateNetworkTopologyStart.emit().defaultPrevented) {
        d("info", this, this._messages.info.validateCanceled);
        return;
      }
      this.state = { type: "executing" };
      const r = {
        outSpatialReference: e.spatialReference?.clone() || null,
        validateArea: this.extentToValidate === "current" || !t.fullExtent ? e.extent.clone() : t.fullExtent.clone()
      };
      this.result = await t.validateTopology(r), this.state = { type: "success", message: this._messages.status.success };
    } catch (e) {
      const { _messages: { errors: { cannotAcquireVersionLock: t, noDirtyAreasInExtent: i, operationOnlyAllowedByOwner: r } } } = this;
      this.result = void 0;
      const o = e, a = o.details?.raw?.extendedCode;
      let c = o.message || this._messages.info.validateCanceled;
      switch (a) {
        case p.noDirtyAreasInExtent:
          c = i;
          break;
        case p.cannotAcquireVersionLockV10:
        case p.cannotAcquireVersionLockV11:
          c = t;
          break;
        case p.operationOnlyAllowedByOwner:
          c = r;
          break;
      }
      this.state = { type: "error-info", message: c };
    } finally {
      this.arcgisValidateNetworkTopologyEnd.emit();
    }
  }
  async _runSetup() {
    this._setupTask?.abort();
    const e = S(async (t) => {
      this.state = { type: "loading" }, this.result = void 0;
      const { view: i } = this;
      if (!i) {
        this.utilityNetwork = void 0, this.state = { type: "error-disable-component", message: this._messages.errors.noView }, d("warn", this, y("view"));
        return;
      }
      if (i.type !== "2d") {
        this.utilityNetwork = void 0, this.state = { type: "error-disable-component", message: this._messages.errors.sceneViewNotSupported };
        return;
      }
      const r = i.map;
      await r.load({ signal: t }), n(t);
      const o = r.utilityNetworks ?? null;
      if (!o?.length) {
        this.utilityNetwork = void 0, this.state = { type: "error-disable-component", message: this._messages.errors.noUtilityNetworks };
        return;
      }
      let a = this.utilityNetwork;
      if ((!a || !o.find((f) => f.id === a?.id)) && (a = o.getItemAt(0)), !a) {
        this.state = { type: "error-disable-component", message: this._messages.errors.noUtilityNetworks }, d("warn", this, y("utilityNetwork"));
        return;
      }
      await a.load({ signal: t }), n(t);
      const g = (Number(a.sourceJSON.currentVersion) || 0) <= 11.1 ? "utilityNetwork" : "advediting", w = await N(a.layerUrl, { signal: t }) ?? void 0;
      n(t);
      const h = new T({ url: w });
      await h.load({ signal: t }), n(t);
      const x = h.user?.username ?? "", v = await V(h, x, g);
      if (n(t), this._utilityNetworks = o, this.utilityNetwork = a, !v) {
        this.state = g === "advediting" ? { type: "error-disable-execute", message: this._messages.errors.noAdvancedEditingUserTypeExtension } : {
          type: "error-disable-execute",
          message: this._messages.errors.noUtilityNetworkServiceUserTypeExtension
        };
        return;
      }
      const m = this._getDirtyAreasLayer(r.allLayers.toArray());
      if (!m) {
        this.state = { type: "error-disable-execute", message: this._messages.errors.noDirtyAreasLayer };
        return;
      }
      await m.load({ signal: t }), n(t), this.state = { type: "ready" };
    });
    this._setupTask = e;
    try {
      await e.promise;
    } catch (t) {
      if (C(t))
        return;
      this.state = { type: "error-disable-execute", message: this._messages.errors.utilityNetworkLoadFailed }, I(t, this, this.state.message);
    } finally {
      this._setupTask === e && (this._setupTask = void 0);
    }
  }
  _renderExtentToValidateCombobox() {
    if (this.state.type !== "error-disable-component")
      return s`<calcite-combobox .disabled=${this.disabled || this.state.type === "disabled" || this.state.type === "executing"} .label=${this._messages.input.selectExtent.label} .labelText=${this._messages.input.selectExtent.label} selection-mode=single-persist @calciteComboboxChange=${(e) => {
        this.extentToValidate = e.target.value;
      }}><calcite-combobox-item .heading=${this._messages.input.selectExtent.options.currentExtent} .selected=${this.extentToValidate === "current"} value=current></calcite-combobox-item><calcite-combobox-item .heading=${this._messages.input.selectExtent.options.entireExtent} .selected=${this.extentToValidate === "entire"} value=entire></calcite-combobox-item></calcite-combobox>`;
  }
  _renderInfoNotice() {
    if (this.state.type === "error-disable-component" || this.state.type === "error-disable-execute" || this.state.type === "error-info" || this.state.type === "success")
      return s`<calcite-notice .closable=${this.state.type === "error-info" || this.state.type === "success"} .kind=${this.state.type === "success" ? "success" : "warning"} open scale=s width=full @calciteNoticeClose=${() => this.state = { type: "ready" }}><div slot=message>${this.state.message}</div></calcite-notice>`;
  }
  _renderStatusIcon() {
    const e = `${this._unVntGuid}_status-icon`;
    switch (this.state.type) {
      case "error-disable-component":
      case "error-disable-execute":
      case "error-info":
        return s`<calcite-icon icon=exclamation-mark-triangle id=${e ?? l} scale=s slot=actions-end></calcite-icon>`;
      case "executing":
        return s`<calcite-action loading disabled slot=actions-end .text=${this._messages.status.executing}></calcite-action>`;
      case "success":
        return s`<calcite-icon icon=check-circle id=${e ?? l} scale=s slot=actions-end></calcite-icon>`;
      default:
        return s`<calcite-icon icon=blank scale=m slot=actions-end></calcite-icon>`;
    }
  }
  _renderUtilityNetworkCombobox() {
    if (!(!this._utilityNetworks || this._utilityNetworks?.length === 1 || this.state.type === "error-disable-component" || this.hideUtilityNetworkSelect))
      return s`<calcite-combobox .disabled=${this.state.type === "executing"} .label=${this._messages.input.selectUtilityNetwork.label} .labelText=${this._messages.input.selectUtilityNetwork.label} selection-mode=single-persist @calciteComboboxChange=${(e) => {
        const t = e.target.value;
        this.utilityNetwork = this._utilityNetworks?.find((i) => i.id === t), this._runSetup();
      }}>${this._utilityNetworks.map((e) => s`<calcite-combobox-item .heading=${e.title} .selected=${e === this.utilityNetwork} .value=${e.id}></calcite-combobox-item>`)}</calcite-combobox>`;
  }
  _renderValidateNetworkTopologyAction() {
    if (this.state.type === "error-disable-component")
      return;
    const e = `${this._unVntGuid}_execute-action`;
    return [
      s`<calcite-action .disabled=${this.disabled || this.state.type === "disabled" || this.state.type === "error-disable-execute" || this.state.type === "executing"} icon=play-f id=${e ?? l} @click=${this._handleValidateNetworkTopologyAction} slot=actions-end .text=${this._messages.actions.validateTopology}></calcite-action>`,
      s`<calcite-tooltip reference-element=${e ?? l}><span>${this._messages.actions.validateTopology}</span></calcite-tooltip>`
    ];
  }
  render() {
    const e = this._renderStatusIcon(), t = this._renderValidateNetworkTopologyAction(), i = this._renderUtilityNetworkCombobox(), r = this._renderExtentToValidateCombobox(), o = this._renderInfoNotice();
    return s`<calcite-panel .loading=${this.state.type === "loading"}><calcite-block collapsible expanded .heading=${this.label}>${e}${t}${i}${r}${o}</calcite-block></calcite-panel>`;
  }
}
k("arcgis-utility-network-validate-network-topology", q);
export {
  q as ArcgisUtilityNetworkValidateNetworkTopology
};
