import { c as L } from "../../chunks/runtime.js";
import { once as P, watch as _ } from "@geoscene/core/core/reactiveUtils.js";
import C from "@geoscene/core/widgets/VersionManagement/VersionManagementViewModel.js";
import { LitElement as N, createEvent as u, noShadowRoot as y, safeClassMap as M } from "@arcgis/lumina";
import { render as F, html as m } from "lit-html";
import { createRef as k, ref as b } from "lit-html/directives/ref.js";
import { u as $ } from "../../chunks/useT9n.js";
import { m as A } from "../../chunks/useViewModel.js";
import { css as T } from "@lit/reactive-element/css-tag.js";
/*! All material copyright GeoScene, All Rights Reserved, unless otherwise specified.
See https://js.geoscene.cn/4.33/geoscene/copyright.txt for details.
v4.33.18 */
const O = T`@layer{.geoscene-version-management{.component-container-flow{width:300px}.invalid-initial-version-notice{margin-bottom:1rem}.service-items-panel{z-index:unset!important}calcite-block{margin:0}}}`, R = A(C), I = "map-components:version-management";
class U extends N {
  constructor() {
    super(...arguments), this.flowElement = k(), this.messages = $({ blocking: !0 }), this.viewModel = R(this), this._isInitialVersionInvalid = /* @__PURE__ */ new Map(), this._initialVersionInfos = [], this._showInvalidFeatureServiceNotice = !1, this.allowEditingDisabled = !1, this.autoDestroyDisabled = !1, this.closable = !1, this.pageSize = 5, this.position = "top-right", this.state = this.viewModel.state, this.versioningStates = this.viewModel.versioningStates, this.geosceneReady = u(), this.geosceneVersioningStateChanged = 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, position: 1, referenceElement: 1, state: 3, versioningStates: 0 };
  }
  static {
    this.styles = O;
  }
  static {
    this.shadowRootOptions = y;
  }
  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() {
    P(() => this.viewModel.state === "ready").then(() => {
      this.initialVersionInfos.forEach((e) => {
        try {
          this._changeToInitialVersion(e);
        } catch (i) {
          console.error(i);
        }
      });
    }), this.manager.onLifecycle(() => [
      _(() => this.viewModel.state, (e) => {
        const { flowElement: { value: i }, versionList: s } = this, t = i?.getElementsByTagName("geoscene-version-management-version-properties")[0];
        if (e === "disabled" && i) {
          t && this._removeVersionPropertiesFlowItem(i), s && this._removeVersionListFlowItem(i);
          return;
        }
        s && (s.versionListElementProps = {
          ...s.versionListElementProps,
          executionError: this.viewModel.executionError
        }, s.versionListElementProps = { ...s.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: s, viewModel: t, viewModel: { state: n } } = this, o = {
      closable: s,
      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 r = F(m`<geoscene-version-management-version-properties .versionPropertiesElementProps=${o} selected show-back-button></geoscene-version-management-version-properties>`, this.versionPropertiesContainer), a = Array.from(r.parentNode.childNodes).find((c) => c.nodeName.toUpperCase() === "GEOSCENE-VERSION-MANAGEMENT-VERSION-PROPERTIES");
    return this.listenOn(a, "geosceneFlowItemBack", () => {
      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, "geosceneCreateVersion", this._handleCreateVersion), this.listenOn(a, "geosceneAlterVersion", 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: s } = this, { alterVersionParameters: t } = e.detail;
    await s.alterVersion(t).then(async (n) => {
      n && this.geosceneVersioningStateChanged.emit({
        type: "version-changed",
        versionIdentifier: t.versionIdentifier,
        versioningState: s.versioningStateLookup.get(t.featureServerUrl)
      }), await this._refreshVersionList(t.featureServerUrl);
    }).finally(() => {
      i && this._removeVersionPropertiesFlowItem(i);
    });
  }
  _handleCreateVersion(e) {
    const { flowElement: { value: i }, viewModel: s } = this, { createVersionParameters: t, switchToVersion: n } = e.detail;
    s.createVersion(t).then(async (o) => {
      o && this.geosceneVersioningStateChanged.emit({
        type: "version-created",
        versionIdentifier: o.versionIdentifier,
        versioningState: s.versioningStateLookup.get(t.featureServerUrl)
      }), n && await this.viewModel.changeVersion(t.featureServerUrl, o.versionIdentifier.name, o.versionIdentifier.guid).then((r) => {
        r && this.geosceneVersioningStateChanged.emit({
          type: "version-switched",
          versionIdentifier: o.versionIdentifier,
          versioningState: s.versioningStateLookup.get(t.featureServerUrl)
        });
      }), await this._refreshVersionList(t.featureServerUrl);
    }).finally(() => {
      i && this._removeVersionPropertiesFlowItem(i);
    });
  }
  _changeToInitialVersion(e) {
    const { _isInitialVersionInvalid: i, viewModel: s } = this, { url: t, name: n } = e, o = s.versioningStateLookup.get(t);
    if (!o)
      throw this._showInvalidFeatureServiceNotice = !0, new Error(`${I} - no versioning state found for feature service ${t}`);
    const r = o?.versionInfos.find((h) => h.versionIdentifier.name === n);
    if (!r)
      throw i.set(t, !0), new Error(`${I} - version ${n} not found in the versioning state for feature service ${t}`);
    const a = r.versionIdentifier, c = o?.currentVersionInfo?.versionIdentifier;
    a.guid !== c?.guid && s.changeVersion(t, a.name, a.guid);
  }
  _handleFlowItemClose() {
    const e = document.querySelector("geoscene-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: s, versionInfo: t } = e.detail, { viewModel: n, flowElement: o } = this;
    switch (i) {
      case "changeVersion": {
        n.changeVersion(s, t.versionIdentifier.name, t.versionIdentifier.guid).then((r) => {
          r && this.geosceneVersioningStateChanged.emit({
            type: "version-switched",
            versionIdentifier: t.versionIdentifier,
            versioningState: n.versioningStateLookup.get(s)
          });
          const { versionList: a } = this;
          a && (a.versionListElementProps = {
            ...a.versionListElementProps,
            currentVersionIdentifier: n.versioningStateLookup.get(s).currentVersionInfo.versionIdentifier
          });
        });
        break;
      }
      case "deleteVersion": {
        n.deleteVersion(s, t.versionIdentifier.name, t.versionIdentifier.guid).then(async (r) => {
          r && this.geosceneVersioningStateChanged.emit({
            type: "version-deleted",
            versionIdentifier: t.versionIdentifier,
            versioningState: n.versioningStateLookup.get(s)
          }), await this._refreshVersionList(s);
        });
        break;
      }
      case "editVersion": {
        const r = this._createVersionPropertiesFlowItem(s, t);
        o.value?.appendChild(r), this.versionList && (this.versionList.selected = !1);
        break;
      }
    }
  }
  async _refreshVersionList(e) {
    const { flowElement: { value: i }, versionList: s, viewModel: t } = this;
    if (i) {
      const n = await t.getVersionInfos(e), o = i.getElementsByTagName("geoscene-version-management-service-item");
      for (const r of o)
        r.serviceItemElementProps.serviceUrl === e && (r.serviceItemElementProps = { ...r.serviceItemElementProps, versionInfos: n });
      s && (s.versionListElementProps = {
        ...s.versionListElementProps,
        currentVersionIdentifier: t.versioningStateLookup.get(e).currentVersionInfo.versionIdentifier,
        versionInfos: n
      });
    }
  }
  _removeVersionListFlowItem(e) {
    for (const i of e.childNodes)
      i.nodeName.toUpperCase() === "GEOSCENE-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() === "GEOSCENE-VERSION-MANAGEMENT-VERSION-PROPERTIES" && e.removeChild(i);
  }
  render() {
    const { allowEditingDisabled: e, closable: i, flowElement: { value: s }, initialVersionInfos: t, _isInitialVersionInvalid: n, label: o, messages: r, mode: a, pageSize: c, versionList: h, viewModel: v, viewModel: { loadError: p, state: d } } = this, w = Array.from(v.serviceNameLookup, ([l, g]) => ({ url: l, name: g })), V = d !== "disabled" ? w.map((l) => {
      const g = {
        allowEditing: !e,
        closable: i,
        currentUser: v.userLookup.get(l.url),
        currentVersionIdentifier: v.versioningStateLookup.get(l.url).currentVersionInfo.versionIdentifier,
        executionError: void 0,
        flowElement: s,
        heading: o,
        initialVersionInfos: t,
        isInitialVersionInvalid: n,
        isVersionAdministrator: v.versionAdministratorLookup.get(l.url),
        isVersioningApiAvailable: (v.serverVersionLookup.get(l.url) ?? 0) >= 11.2,
        mode: a,
        pageSize: c,
        serviceName: l.name,
        state: d,
        serviceUrl: l.url,
        strings: r,
        versionInfos: v.versioningStateLookup.get(l.url)?.versionInfos ?? []
      };
      return m`<geoscene-version-management-service-item .serviceItemElementProps=${g} @geosceneFlowItemBack=${() => {
        s && (this._removeVersionListFlowItem(s), this.versionList = void 0);
      }} @geosceneFlowItemClose=${() => this._handleFlowItemClose()} @geosceneGetVersions=${async (f) => {
        await this._refreshVersionList(f.detail.serviceUrl);
      }} @geosceneManageVersion=${this._handleManageVersionAction} @geosceneNewVersion=${this._handleNewVersionAction} @geosceneCreateVersionList=${(f) => this.versionList = f.detail}></geoscene-version-management-service-item>`;
    }) : void 0, E = d === "disabled" && p != null ? m`<calcite-notice class="notice" kind=warning open scale=s slot=footer width=full><div slot=message>${this._getLoadError(p)}</div></calcite-notice>` : void 0, S = this._showInvalidFeatureServiceNotice ? m`<calcite-notice closable kind=warning open scale=s slot=content-top width=full icon @calciteNoticeClose=${() => this._showInvalidFeatureServiceNotice = !1}><div slot=title>${r.headers.invalidInitialFeatureService}</div><div slot=message>${r.loadErrors.invalidInitialFeatureService}</div></calcite-notice>` : void 0;
    return m`<div class="geoscene-version-management"><calcite-flow custom-item-selectors="geoscene-version-management-version-list, geoscene-version-management-version-properties" class=${M(this.mode === "dialog" ? "" : "component-container-flow")} ${b(this.flowElement)}><calcite-flow-item .closable=${this.closable} .heading=${o ?? void 0} @calciteFlowItemClose=${() => this._handleFlowItemClose()} .selected=${!h}>${S}<calcite-panel class="service-items-panel" .loading=${d === "loading" || d === "executing"}>${V}${E}</calcite-panel></calcite-flow-item></calcite-flow></div>`;
  }
}
L("geoscene-version-management", U);
export {
  U as GeosceneVersionManagement
};