/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
import { c as w } from "../../chunks/runtime.js";
import { css as b, html as o } from "lit";
import { a as h } from "../../chunks/queryUtils.js";
import { g as f } from "../../chunks/mapViewUtils.js";
import { u as g } from "../../chunks/useT9n.js";
import { createRef as d, ref as p } from "lit-html/directives/ref.js";
import { LitElement as y, createEvent as n, noShadowRoot as F, safeClassMap as v } from "@arcgis/lumina";
import * as $ from "@arcgis/core/core/reactiveUtils.js";
const k = b`@layer{:host{display:block!important}.display-none{display:none}.padding-1{padding:1rem}.position-relative{position:relative}.overflow-auto{overflow:auto}.height-full{height:100%}.paste-component{--arcgis-paste-height: 100%;--arcgis-paste-width: 100%;height:100%;width:100%}.position-static{position:static!important}.z-index-500{z-index:500!important}.margin-top-10{margin-top:10px}card-manager{display:block}}`;
class S extends y {
  constructor() {
    super(), this.customInfoText = "", this.enableEditGeometry = !1, this.enableSnapping = !1, this.isMobile = !1, this.zoomAndScrollToSelected = !1, this.selectedFeaturesIds = [], this.enableCreateFeatures = !0, this.createBtnLabel = "", this.selectingFeatureFromMap = !1, this.showSketchWidgets = !1, this.mapComponentId = "", this.pasteEnabled = !1, this.showCopyPasteActions = !1, this.allowedPasteLayerIds = [], this._cardLoading = !1, this._graphics = [], this._showCreateFeatureComponent = !1, this._showSubmitBtn = !1, this._activeFeatureCreationCount = 1, this._createAndBackBtnDisabled = !1, this._translations = g({ name: "card-manager", blocking: !0 }), this._isFeatureCreated = !1, this._createFeature = d(), this._pasteComponent = d(), this.createWorkFlowStarted = n(), this.backFromCreateWorkFlow = n(), this.featureOrRecordSubmitted = n(), this.featuresCopied = n(), this.featuresPasted = n(), this.disablePaste = n(), this._handleCreateAndBackBtn = (e) => {
      this._createFeatureEditor && (this._createAndBackBtnDisabled = e);
    }, this._featuresAdded = () => {
      this._pasteComponent.value && this._resetPasteWorkflow();
    }, this._initCreateComponent = () => {
      this._showCreateFeatureComponent = !0;
    }, this._createFeatureEditorInitialized = (e) => {
      this._createFeatureEditor = e.detail;
    }, this._createFeatureEditorClosed = () => {
      this._createFeatureEditor = void 0;
    }, this._pasteComponentReady = async () => {
      const e = this._pasteComponent.value;
      if (e && this.mapComponentId && e.referenceElement === void 0) {
        const t = document.getElementById(this.mapComponentId);
        await t.viewOnReady(), e.referenceElement = t;
      }
      e && !this._clipboardWatchHandle && (this._clipboardWatchHandle = $.watch(() => e.clipboard.hasItems, (t) => {
        t || this.disablePaste.emit();
      }));
    }, this._applyPasteCommand = async (e) => {
      const t = new Promise((a, s) => {
        if (!this._pasteComponent.value) {
          console.error("Paste failed: paste component is not available."), a();
          return;
        }
        try {
          e.detail.applySet ? this._pasteComponent.value.writeChanges(e.detail.applySet).then(() => {
            this._resetPasteWorkflow(), a();
          }).catch((i) => {
            console.log(i), s(i);
          }) : a();
        } catch (i) {
          s(i), console.error("Paste failed:", i);
        }
      });
      e.detail.completionCallback = t;
    }, this.listenOn(window, "featureSelectionChange", this.featureSelectionChange), this.listenOn(window, "layerSelectionChange", this.layerSelectionChange), this.listenOn(window, "mapChanged", this.mapChanged), this.listenOn(window, "relatedRecordToggled", this.relatedRecordToggled), this.listenOn(window, "copyFeatures", this._copyFeatures), this.listenOn(window, "pasteFeatures", this._pasteFeatures), this.listenOn(window, "featuresAdded", this._featuresAdded), this.listenOn(window, "initCreateComponent", this._initCreateComponent), this.listenOn(window, "createFeatureEditorInitialized", this._createFeatureEditorInitialized), this.listenOn(window, "createFeatureEditorClosed", this._createFeatureEditorClosed), this.listenOn(window, "continueEditing", () => this._handleCreateAndBackBtn(!1)), this.listenOn(window, "beforeLayerSelectionChange", () => this._handleCreateAndBackBtn(!0)), this.listenOn(window, "beforeMapInfoChange", () => this._handleCreateAndBackBtn(!0)), this.listenOn(window, "beforeFeatureSelectionChange", () => this._handleCreateAndBackBtn(!0));
  }
  static {
    this.properties = { customInfoText: 1, enableEditGeometry: 5, enableSnapping: 5, isMobile: 5, layerOrTable: 0, mapView: 0, zoomAndScrollToSelected: 5, selectedFeaturesIds: 0, enableCreateFeatures: 5, createBtnLabel: 1, selectingFeatureFromMap: 5, showSketchWidgets: 5, mapComponentId: 1, pasteEnabled: 5, showCopyPasteActions: 5, allowedPasteLayerIds: 0, _cardLoading: 16, _graphics: 16, _showCreateFeatureComponent: 16, _showSubmitBtn: 16, _activeFeatureCreationCount: 16, _createAndBackBtnDisabled: 16, _translations: 16 };
  }
  static {
    this.styles = k;
  }
  static {
    this.shadowRootOptions = F;
  }
  async featureSelectionChange(e) {
    this._showCreateFeatureComponent && !this._isFeatureCreated && this._backFromCreateFeature();
    const t = e.detail;
    this._graphics = await this._getFeaturesByIds(t);
  }
  async layerSelectionChange(e) {
    this._showCreateFeatureComponent && this._backFromCreateFeature();
    const t = e.detail[0];
    this.layerOrTable = this.mapView ? await f(this.mapView, t) : void 0, await this._resetPasteWorkflow();
  }
  async mapChanged(e) {
    await this._resetPasteWorkflow();
  }
  async relatedRecordToggled(e) {
    const t = e.detail;
    this.layerOrTable = t;
  }
  async _copyFeatures(e) {
    if (!this._pasteComponent.value)
      return;
    const t = e.detail.featuresIds, a = this.layerOrTable, s = await h(t, a, [], !0, this.mapView?.spatialReference), i = [];
    s.forEach((r) => {
      const l = {
        layer: r.layer,
        graphic: r,
        type: "feature"
      };
      i.push(l);
    }), this._pasteComponent.value.clipboard.setData(i), this.featuresCopied.emit(), this.requestUpdate();
  }
  async _pasteFeatures(e) {
    if (!this._pasteComponent.value) {
      console.error("Paste failed: paste component is not available.");
      return;
    }
    try {
      this._pasteComponent.value.closed = !1, await this._pasteComponent.value.showClipboardItems(!0), this.layerOrTable?.isTable || await this._pasteComponent.value.startMoveClipboard(!0), this.featuresPasted.emit();
    } catch (t) {
      console.error("Paste failed:", t);
    }
  }
  _getLayerPermissionsCheck() {
    const e = this.allowedPasteLayerIds?.length > 0 ? this.allowedPasteLayerIds.map(String) : this.layerOrTable?.id !== void 0 ? [String(this.layerOrTable.id)] : [], t = new Set(e);
    return {
      canCreate: (a) => t.has(String(a.id)) && a.editingEnabled && a.capabilities?.operations?.supportsAdd,
      canUpdate: (a) => t.has(String(a.id)) && a.editingEnabled && a.capabilities?.operations?.supportsUpdate
    };
  }
  async _resetPasteWorkflow() {
    if (this._pasteComponent.value)
      try {
        await this._pasteComponent.value.showClipboardItems(!1), await this._pasteComponent.value.cancelMoveClipboard();
      } catch (e) {
        console.error("Reset paste workflow failed:", e);
      } finally {
        this._pasteComponent.value.closed = !0;
      }
  }
  async load() {
    this.selectedFeaturesIds?.length > 0 && (this._graphics = await this._getFeaturesByIds(this.selectedFeaturesIds));
  }
  disconnectedCallback() {
    super.disconnectedCallback(), this._clipboardWatchHandle?.remove(), this._clipboardWatchHandle = void 0;
  }
  render() {
    const e = (this._pasteComponent.value?.closed || !this.showCopyPasteActions) && this._graphics?.length > 0, t = this._pasteComponent.value?.closed ? "display-none" : "", a = this._graphics?.length === 0 && this._showCreateFeatureComponent ? "" : "display-none", s = this._graphics?.length > 0 || this._showCreateFeatureComponent || !this._pasteComponent.value?.closed && this.showCopyPasteActions ? "display-none" : "", i = this.layerOrTable?.isTable, r = this.customInfoText ? this.customInfoText : this.selectingFeatureFromMap ? this._translations.selectFeaturesFromMapToStart : this._translations.selectFeaturesToStart, l = this.enableCreateFeatures && this.layerOrTable?.editingEnabled && this.layerOrTable?.capabilities?.operations?.supportsAdd, c = this.createBtnLabel ? this.createBtnLabel : i ? this._translations.createRecord : this._translations.createFeature, u = !this.layerOrTable, m = this.enableSnapping && !this.layerOrTable?.isTable, C = this.layerOrTable?.isTable ? ["paste"] : ["paste", "paste-as"], _ = !this.layerOrTable?.isTable;
    return o`<calcite-panel><div class="overflow-auto height-full">${e && o`<calcite-shell class=${"position-relative"}><div class="position-static z-index-500 height-full"><info-card .allowEditing=${this.layerOrTable?.editingEnabled} .enableEditGeometry=${this.enableEditGeometry} .enableSnapping=${m} .graphics=${this._graphics.reverse()} .isLoading=${this._cardLoading} .isMobile=${this.isMobile} .mapView=${this.mapView} .featuresReferenceId=${this.mapComponentId} position=relative .pasteEnabled=${this.pasteEnabled} show-close-btn .showCopyPasteActions=${this.showCopyPasteActions}></info-card></div></calcite-shell>` || ""}<calcite-shell class=${`position-relative ${s}`}><calcite-panel><div class=padding-1><calcite-notice .icon=${this.selectingFeatureFromMap ? "map" : "table"} icon-flip-rtl open><div slot=message>${r}</div></calcite-notice></div>${!this.isMobile && l && o`<calcite-button .disabled=${u} @click=${() => this._createFeatureBtnClicked()} slot=footer width=full>${c}</calcite-button>` || ""}</calcite-panel></calcite-shell><calcite-shell class=${`position-relative ${a}`}><calcite-flow-item selected><calcite-panel .heading=${c}><calcite-action class="back-button hydrated" .disabled=${this._createAndBackBtnDisabled} icon=chevron-left @click=${this._backFromCreateFeature} scale=s slot=header-actions-start .text=${this._translations.back}></calcite-action>${this.getEditorComponent()}${this._showSubmitBtn && o`<calcite-button appearance=solid class="footer-top-button footer-button" .disabled=${this._createAndBackBtnDisabled} @click=${() => this._createFeature.value && void this._createFeature.value.submit()} slot=footer width=full>${this._activeFeatureCreationCount > 1 ? this._translations.createMultiple.replace("{{n}}", String(this._activeFeatureCreationCount)) : this._translations.create}</calcite-button>` || ""}</calcite-panel></calcite-flow-item></calcite-shell>${this.showCopyPasteActions && o`<calcite-panel class=${v(t)}><arcgis-paste always-show-feature-form class=${`paste-component ${t}`} closed @arcgisReady=${this._pasteComponentReady} @arcgisApplyPasteCommand=${this._applyPasteCommand} @arcgisClose=${() => {
      this._resetPasteWorkflow();
    }} paste-with-multiple-layers-enabled paste-with-multiple-features-enabled .layerPermissionsCheck=${this._getLayerPermissionsCheck()} .supportedCommands=${C} .view=${this.mapView} ${p(this._pasteComponent)}>${_ && o`<calcite-notice slot=commands-page-message class="margin-top-10" open icon=move><div slot=message>${this._translations.moveClipboardFeatures}</div></calcite-notice>` || ""}</arcgis-paste></calcite-panel>` || ""}</div></calcite-panel>`;
  }
  getEditorComponent() {
    const e = this.enableSnapping && !this.layerOrTable?.isTable && this.enableCreateFeatures;
    return o`<div>${this._showCreateFeatureComponent && o`<create-feature allow-multiple-creation customize-submit .enableSnapping=${e} .mapView=${this.mapView} .isMobile=${this.isMobile} @activeFeatureCountChange=${(t) => {
      this._activeFeatureCreationCount = t.detail, this._showSubmitBtn = this._activeFeatureCreationCount > 0;
    }} @drawComplete=${() => {
      this._showSubmitBtn = !0;
    }} @editingAttachment=${(t) => {
      this._showSubmitBtn = !t.detail;
    }} @progressStatus=${() => {
      setTimeout(() => {
        this._isFeatureCreated = !1;
      }, 2e3);
    }} @success=${this._featureCreated} .showSketchWidgets=${this.showSketchWidgets} .selectedLayerId=${this.layerOrTable?.id} show-guiding-msg .showLayerVisibilityMsg=${this.layerOrTable?.visible === !1} ${p(this._createFeature)}></create-feature>` || ""}</div>`;
  }
  async _getFeaturesByIds(e) {
    return (e.length > 0 && this.layerOrTable && this.mapView ? await h(e, this.layerOrTable, [], !0, this.mapView?.spatialReference) : []).sort((a, s) => e.indexOf(Number(a.getObjectId())) - e.indexOf(Number(s.getObjectId())));
  }
  _createFeatureBtnClicked() {
    this._showCreateFeatureComponent = !0, this._handleCreateAndBackBtn(!1), this.createWorkFlowStarted.emit();
  }
  async _backFromCreateFeature() {
    this._createFeatureEditor && await this._validateActiveEdits() && (this._showCreateFeatureComponent = !1, this.backFromCreateWorkFlow.emit(), this._showSubmitBtn = !1, this._handleCreateAndBackBtn(!1));
  }
  async _validateActiveEdits() {
    let e = !0;
    if (this._createFeatureEditor && this._hasPendingEdits()) {
      let a = !1;
      try {
        this._handleCreateAndBackBtn(!0), this._createFeatureEditor.activeWorkflow && await this._createFeatureEditor.activeWorkflow.cancel({ force: !1 });
      } catch (s) {
        a = s?.name === "workflow:cancel-denied";
      }
      a && (this._handleCreateAndBackBtn(!1), e = !1);
    }
    return e;
  }
  _hasPendingEdits() {
    return this._createFeatureEditor?.activeWorkflow?.hasPendingEdits;
  }
  _featureCreated() {
    this._showCreateFeatureComponent = !1, this._showSubmitBtn = !1, this._isFeatureCreated = !0, this.featureOrRecordSubmitted.emit();
  }
}
w("card-manager", S);
export {
  S as CardManager
};
