/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
import { c as S } from "../../chunks/runtime.js";
import { once as L, watch as P } from "@arcgis/core/core/reactiveUtils.js";
import _ from "@arcgis/core/versionManagement/VersionManager.js";
import { LitElement as b, createEvent as u } from "@arcgis/lumina";
import { css as N, render as C, html as v } from "lit";
import { createRef as F, ref as M } from "lit/directives/ref.js";
import { u as k } from "../../chunks/useT9n.js";
import { m as x } from "../../chunks/useViewModel.js";
import { d as $ } from "../../chunks/component-utils.js";
import { rethrowError as A } from "@arcgis/toolkit/log";
const T = N`: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;min-height:var(--arcgis-internal-panel-height-md, 420px);height:100%}calcite-notice{margin:var(--calcite-spacing-md)}`, O = x(_), w = "map-components:version-management";
class U extends b {
  constructor() {
    super(...arguments), this.flowElement = F(), this.messages = k({ blocking: !0 }), this.viewModel = O(this), this._isInitialVersionInvalid = /* @__PURE__ */ new Map(), this._initialVersionInfos = [], this._showInvalidFeatureServiceNotice = !1, this.allowEditingDisabled = !1, this.autoDestroyDisabled = !1, this.closable = !1, this.pageSize = 5, this.state = this.viewModel.state, this.versioningStates = this.viewModel.versioningStates, this.view = this.viewModel.view, this.arcgisReady = u(), this.arcgisVersioningStateChanged = u();
  }
  static {
    this.properties = { versionList: 16, _showInvalidFeatureServiceNotice: 16, allowEditingDisabled: 5, autoDestroyDisabled: 5, closable: 7, initialVersionInfos: 0, icon: 1, label: 3, messageOverrides: 0, mode: 1, pageSize: 9, referenceElement: 1, state: 32, versioningStates: 0, view: 0 };
  }
  static {
    this.styles = T;
  }
  get initialVersionInfos() {
    return this._initialVersionInfos;
  }
  set initialVersionInfos(e) {
    this._initialVersionInfos = e.map((i) => ({
      ...i,
      url: this._removeTrailingSlash(i.url)
    }));
  }
  async destroy() {
    await this.manager.destroy();
  }
  async load() {
    L(() => this.viewModel.state === "ready").then(() => {
      this.initialVersionInfos.forEach((e) => {
        try {
          this._changeToInitialVersion(e);
        } catch (i) {
          A(this)(i);
        }
      });
    }), this.manager.onLifecycle(() => [
      P(() => this.viewModel.state, (e) => {
        const { flowElement: { value: i }, versionList: r } = this, t = i?.getElementsByTagName("arcgis-version-management-version-properties")[0];
        if (e === "disabled" && i) {
          t && this._removeVersionPropertiesFlowItem(i), r && this._removeVersionListFlowItem(i);
          return;
        }
        r && (r.versionListElementProps = {
          ...r.versionListElementProps,
          executionError: this.viewModel.executionError
        }, r.versionListElementProps = { ...r.versionListElementProps, state: e }), t && (t.versionPropertiesElementProps = {
          ...t.versionPropertiesElementProps,
          state: e
        });
      })
    ]);
  }
  disconnectedCallback() {
    super.disconnectedCallback(), this.versionPropertiesContainer?.remove();
  }
  _removeTrailingSlash(e) {
    return e.replace(/\/+$/u, "");
  }
  _createVersionPropertiesFlowItem(e, i) {
    const { closable: r, viewModel: t, viewModel: { state: n } } = this, o = {
      closable: r,
      currentUser: t.userLookup.get(e),
      isVersionAdministrator: t.versionAdministratorLookup.get(e),
      serviceUrl: e,
      state: n,
      strings: this.messages,
      versionInfo: i
    };
    this.versionPropertiesContainer = document.createElement("div");
    const s = C(v`<arcgis-version-management-version-properties .versionPropertiesElementProps=${o} selected show-back-button></arcgis-version-management-version-properties>`, this.versionPropertiesContainer), a = Array.from(s.parentNode.childNodes).find((c) => c.nodeName.toUpperCase() === "ARCGIS-VERSION-MANAGEMENT-VERSION-PROPERTIES");
    return this.listenOn(a, "arcgisFlowItemBack", () => {
      this._removeVersionPropertiesFlowItem(this.flowElement.value);
    }), this.listenOn(a, "calciteFlowItemBack", (c) => {
      c.preventDefault(), this._removeVersionPropertiesFlowItem(this.flowElement.value), this.versionList && (this.versionList.selected = !0);
    }), this.listenOn(a, "calciteFlowItemClose", this._handleFlowItemClose), this.listenOn(a, "arcgisCreateVersion", this._handleCreateVersion), this.listenOn(a, "arcgisAlterVersion", this._handleAlterVersion), a;
  }
  _getLoadError(e) {
    const { messages: i } = this;
    switch (e) {
      case "no-feature-services":
        return i.loadErrors.noFeatureServices;
      case "no-view-property":
        return i.loadErrors.noViewProperty;
      default:
        return e;
    }
  }
  async _handleAlterVersion(e) {
    const { flowElement: { value: i }, viewModel: r } = this, { alterVersionParameters: t } = e.detail;
    await r.alterVersion(t).then(async (n) => {
      n && this.arcgisVersioningStateChanged.emit({
        type: "version-changed",
        versionIdentifier: t.versionIdentifier,
        versioningState: r.versioningStateLookup.get(t.featureServerUrl)
      }), await this._refreshVersionList(t.featureServerUrl);
    }).finally(() => {
      i && this._removeVersionPropertiesFlowItem(i);
    });
  }
  _handleCreateVersion(e) {
    const { flowElement: { value: i }, viewModel: r } = this, { createVersionParameters: t, switchToVersion: n } = e.detail;
    r.createVersion(t).then(async (o) => {
      o && this.arcgisVersioningStateChanged.emit({
        type: "version-created",
        versionIdentifier: o.versionIdentifier,
        versioningState: r.versioningStateLookup.get(t.featureServerUrl)
      }), n && await this.viewModel.changeVersion(t.featureServerUrl, o.versionIdentifier.name, o.versionIdentifier.guid).then((s) => {
        s && this.arcgisVersioningStateChanged.emit({
          type: "version-switched",
          versionIdentifier: o.versionIdentifier,
          versioningState: r.versioningStateLookup.get(t.featureServerUrl)
        });
      }), await this._refreshVersionList(t.featureServerUrl);
    }).finally(() => {
      i && this._removeVersionPropertiesFlowItem(i);
    });
  }
  _changeToInitialVersion(e) {
    const { _isInitialVersionInvalid: i, viewModel: r } = this, { url: t, name: n } = e, o = r.versioningStateLookup.get(t);
    if (!o)
      throw this._showInvalidFeatureServiceNotice = !0, new Error(`${w} - no versioning state found for feature service ${t}`);
    const s = o?.versionInfos.find((m) => m.versionIdentifier.name === n);
    if (!s)
      throw i.set(t, !0), new Error(`${w} - version ${n} not found in the versioning state for feature service ${t}`);
    const a = s.versionIdentifier, c = o?.currentVersionInfo?.versionIdentifier;
    a.guid !== c?.guid && r.changeVersion(t, a.name, a.guid);
  }
  _handleFlowItemClose() {
    const e = document.querySelector("arcgis-version-management");
    e.parentElement?.removeChild(e);
  }
  async _handleNewVersionAction(e) {
    const i = this._createVersionPropertiesFlowItem(e.detail.serviceUrl, void 0);
    this.flowElement.value?.appendChild(i), this.versionList && (this.versionList.selected = !1);
  }
  async _handleManageVersionAction(e) {
    const { actionType: i, serviceUrl: r, versionInfo: t } = e.detail, { viewModel: n, flowElement: o } = this;
    switch (i) {
      case "changeVersion": {
        n.changeVersion(r, t.versionIdentifier.name, t.versionIdentifier.guid).then((s) => {
          s && this.arcgisVersioningStateChanged.emit({
            type: "version-switched",
            versionIdentifier: t.versionIdentifier,
            versioningState: n.versioningStateLookup.get(r)
          });
          const { versionList: a } = this;
          a && (a.versionListElementProps = {
            ...a.versionListElementProps,
            currentVersionIdentifier: n.versioningStateLookup.get(r).currentVersionInfo.versionIdentifier
          });
        });
        break;
      }
      case "deleteVersion": {
        n.deleteVersion(r, t.versionIdentifier.name, t.versionIdentifier.guid).then(async (s) => {
          s && this.arcgisVersioningStateChanged.emit({
            type: "version-deleted",
            versionIdentifier: t.versionIdentifier,
            versioningState: n.versioningStateLookup.get(r)
          }), await this._refreshVersionList(r);
        });
        break;
      }
      case "editVersion": {
        const s = this._createVersionPropertiesFlowItem(r, t);
        o.value?.appendChild(s), this.versionList && (this.versionList.selected = !1);
        break;
      }
    }
  }
  async _refreshVersionList(e) {
    const { flowElement: { value: i }, versionList: r, viewModel: t } = this;
    if (i) {
      const n = await t.getVersionInfos(e), o = i.getElementsByTagName("arcgis-version-management-service-item");
      for (const s of o)
        s.serviceItemElementProps.serviceUrl === e && (s.serviceItemElementProps = { ...s.serviceItemElementProps, versionInfos: n });
      r && (r.versionListElementProps = {
        ...r.versionListElementProps,
        currentVersionIdentifier: t.versioningStateLookup.get(e).currentVersionInfo.versionIdentifier,
        versionInfos: n
      });
    }
  }
  _removeVersionListFlowItem(e) {
    for (const i of e.childNodes)
      i.nodeName.toUpperCase() === "ARCGIS-VERSION-MANAGEMENT-VERSION-LIST" && (e.removeChild(i), this.versionList = void 0), i.nodeName.toUpperCase() === "CALCITE-FLOW-ITEM" && (i.hidden = !1);
  }
  _removeVersionPropertiesFlowItem(e) {
    for (const i of e.childNodes)
      i.nodeName.toUpperCase() === "ARCGIS-VERSION-MANAGEMENT-VERSION-PROPERTIES" && e.removeChild(i);
  }
  render() {
    const { allowEditingDisabled: e, closable: i, flowElement: { value: r }, initialVersionInfos: t, _isInitialVersionInvalid: n, label: o, messages: s, mode: a, pageSize: c, versionList: m, viewModel: d, viewModel: { loadError: f, state: g } } = this, I = Array.from(d.serviceNameLookup, ([l, h]) => ({ url: l, name: h })), V = g !== "disabled" ? I.map((l) => {
      const h = {
        allowEditing: !e,
        closable: i,
        currentUser: d.userLookup.get(l.url),
        currentVersionIdentifier: d.versioningStateLookup.get(l.url).currentVersionInfo.versionIdentifier,
        executionError: void 0,
        flowElement: r,
        heading: o,
        initialVersionInfos: t,
        isInitialVersionInvalid: n,
        isVersionAdministrator: d.versionAdministratorLookup.get(l.url),
        isVersioningApiAvailable: (d.serverVersionLookup.get(l.url) ?? 0) >= 11.2,
        mode: a,
        pageSize: c,
        serviceName: l.name,
        state: g,
        serviceUrl: l.url,
        strings: s,
        versionInfos: d.versioningStateLookup.get(l.url)?.versionInfos ?? []
      };
      return v`<arcgis-version-management-service-item .serviceItemElementProps=${h} @arcgisFlowItemBack=${() => {
        r && (this._removeVersionListFlowItem(r), this.versionList = void 0);
      }} @arcgisFlowItemClose=${() => this._handleFlowItemClose()} @arcgisGetVersions=${async (p) => {
        await this._refreshVersionList(p.detail.serviceUrl);
      }} @arcgisManageVersion=${this._handleManageVersionAction} @arcgisNewVersion=${this._handleNewVersionAction} @arcgisCreateVersionList=${(p) => this.versionList = p.detail}></arcgis-version-management-service-item>`;
    }) : void 0, E = g === "disabled" && f != null ? v`<calcite-notice kind=warning open scale=s slot=footer width=full><div slot=message>${this._getLoadError(f)}</div></calcite-notice>` : void 0, y = this._showInvalidFeatureServiceNotice ? v`<calcite-notice closable kind=warning open scale=s slot=content-top width=full icon @calciteNoticeClose=${() => this._showInvalidFeatureServiceNotice = !1}><div slot=title>${s.headers.invalidInitialFeatureService}</div><div slot=message>${s.loadErrors.invalidInitialFeatureService}</div></calcite-notice>` : void 0;
    return v`<div class="root"><calcite-flow custom-item-selectors="arcgis-version-management-version-list, arcgis-version-management-version-properties" ${M(this.flowElement)}><calcite-flow-item .closable=${this.closable} .heading=${$(o) ? s.label : o} @calciteFlowItemClose=${() => this._handleFlowItemClose()} .selected=${!m}>${y}${g === "loading" || g === "executing" ? v`<calcite-loader .label=${`${s.label} - loading`}></calcite-loader>` : v`<calcite-panel>${V}${E}</calcite-panel>`}</calcite-flow-item></calcite-flow></div>`;
  }
}
S("arcgis-version-management", U);
export {
  U as ArcgisVersionManagement
};
