/* COPYRIGHT Esri - https://js.arcgis.com/1.2/LICENSE.txt */
import { c as customElement } from "../../chunks/runtime.js";
import { a as getAllFeatureLayers } from "../../chunks/mapViewUtils.js";
import { u as useT9n } from "../../chunks/useT9n.js";
import { css, html } from "lit";
import { createRef, ref } from "lit-html/directives/ref.js";
import { LitElement, createEvent, noShadowRoot, safeClassMap } from "@arcgis/lumina";
import Editor from "@arcgis/core/widgets/Editor";
import * as reactiveUtils from "@arcgis/core/core/reactiveUtils";
const styles = css`@layer{
/** @license
 * Copyright 2025 Esri
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

:host {
  display: block;
}

#feature-form {
  padding-top: 0px;
}

.esri-editor__prompt--danger {
  position: relative !important;
  width: 100% !important;
  background-color: var(--calcite-color-foreground-1) !important;
}

.esri-feature__content-node {
  background-color: var(--calcite-color-foreground-1) !important;
}

.hide-editor-toolbar .esri-editor__panel-toolbar {
  display: none !important;
}

.position-absolute {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  overflow: auto;
}

/* override the padding of the feature form */
.esri-editor__panel-content {
  padding-block: 10px !important;
}
}`;
class EditCard extends LitElement {
  constructor() {
    super();
    this.enableEditGeometry = false;
    this.enableSnapping = false;
    this.graphicIndex = 0;
    this.graphics = [];
    this.open = false;
    this.allowMultipleEditing = false;
    this._editorLoading = false;
    this._translations = useT9n({ name: "edit-card", blocking: true });
    this._editContainer = createRef();
    this._shouldClose = false;
    this._shouldEmitEditsComplete = false;
    this.closeEdit = createEvent();
    this.editorInitialized = createEvent();
    this.editsComplete = createEvent();
    this.refreshGraphics = createEvent();
    this.creatingFeature = createEvent();
    this.listenOn(window, "featureSelectionChange", this.featureSelectionChange);
    this.listenOn(window, "mapChanged", this.mapChanged);
  }
  static {
    this.properties = { enableEditGeometry: [5, {}, { type: Boolean }], enableSnapping: [5, {}, { type: Boolean }], graphicIndex: [9, {}, { type: Number }], graphics: [0, {}, { attribute: false }], mapView: [0, {}, { attribute: false }], open: [5, {}, { type: Boolean }], allowMultipleEditing: [5, {}, { type: Boolean }], _editorLoading: [16, {}, { state: true }], _translations: [16, {}, { state: true }] };
  }
  static {
    this.styles = styles;
  }
  static {
    this.shadowRootOptions = noShadowRoot;
  }
  async graphicsWatchHandler() {
    if (this.graphics.length === 0 && this.open) {
      await this._closeEdit(true);
    }
  }
  async openWatchHandler(v) {
    if (v && this.graphics?.length > 0 && this.graphicIndex > -1) {
      this._editorLoading = true;
      await this._initEditorWidget();
      if (this.graphicIndex > -1 && this.graphics.length > 0 && this.open && !this._shouldClose) {
        await this._startUpdate();
      }
      this._editorLoading = false;
    }
    if (!v) {
      await this._closeEdit(true);
    }
  }
  async featureSelectionChange() {
    if (this.open) {
      await this._closeEdit(false);
    }
  }
  async mapChanged() {
    if (this.open) {
      await this._closeEdit(false);
    }
  }
  willUpdate(changes) {
    if (changes.has("graphics")) {
      void this.graphicsWatchHandler();
    }
    if (changes.has("open") && (this.hasUpdated || this.open !== false)) {
      void this.openWatchHandler(this.open);
    }
    if (this.graphics?.length > 0 && this.graphics[0]?.layer) {
      this._layer = this.graphics[0].layer;
      if (this._layerEditHandle) {
        this._layerEditHandle.remove();
      }
      const layer = this._layer.type === "subtype-sublayer" ? this._layer.parent : this._layer;
      if (layer) {
        this._layerEditHandle = layer.on("edits", () => {
          this._shouldEmitEditsComplete = true;
        });
      }
    }
  }
  render() {
    const editDisabled = this.graphics?.length > 0 && this.graphics[0] ? !this.graphics[0].layer.editingEnabled : true;
    const tableNodeClass = this._editorLoading ? "display-none" : "position-absolute";
    const loadingClass = this._editorLoading ? "" : "display-none";
    return html`<div class="position-absolute">${editDisabled ? html`<calcite-notice kind=warning open slot=content-top width=full><div slot=message>${this._translations.enableEditing}</div></calcite-notice>` : void 0}<div class="position-absolute"><div class=${safeClassMap(tableNodeClass)} id=feature-form ${ref(this._editContainer)}></div><calcite-loader class=${safeClassMap(loadingClass)} label scale=s></calcite-loader></div></div>`;
  }
  async _initEditorWidget() {
    if (this.mapView && this.graphics && this.graphics.length > 0 && this.graphics[0]) {
      if (this._editor) {
        this._editor.destroy();
      }
      const container = document.createElement("div");
      const layers = await getAllFeatureLayers(this.mapView);
      const showSnappingTools = this.enableSnapping && this.enableEditGeometry;
      const layerInfos = layers.map((layer) => {
        return {
          layer,
          geometryUpdatesEnabled: this.enableEditGeometry
        };
      });
      this._editor = new Editor({
        view: this.mapView,
        layerInfos,
        visibleElements: {
          flow: true,
          settingsMenu: showSnappingTools,
          sketch: false,
          snappingControls: showSnappingTools
        },
        container
      });
      if (this._attachmentHandle && this._activeWorkflowHandle) {
        this._attachmentHandle.remove();
        this._activeWorkflowHandle.remove();
      }
      this._attachmentHandle = reactiveUtils.when(() => this._editor?.viewModel.state === "adding-attachment" || this._editor?.viewModel.state === "editing-attachment" || this._editor?.viewModel.state === "creating-features", () => {
        this._shouldClose = false;
      });
      this._activeWorkflowHandle = reactiveUtils.watch(() => this._editor?.viewModel.activeWorkflow, (activeWorkflow) => {
        if (activeWorkflow?.type === "update" || activeWorkflow?.type === "create-features") {
          this._shouldClose = false;
        }
        if (!activeWorkflow?.type && !activeWorkflow?.hasPendingEdits && !this._editor?.activeWorkflow || !this._editor?.activeWorkflow?.started) {
          this.allowMultipleEditing = false;
          this.open = false;
        }
      });
      reactiveUtils.watch(() => this._editor?.viewModel.state, (state) => {
        if (state === "creating-features" && this.graphics[0].layer.isTable && !(this._editor?.viewModel).featureTemplatesLayers.items[0].isTable) {
          this.creatingFeature.emit();
        }
        if (this._shouldEmitEditsComplete && state === "ready" && !this._editor?.activeWorkflow) {
          this.editsComplete.emit();
          this._shouldEmitEditsComplete = false;
        }
      });
      if (!this.enableSnapping) {
        container.classList.add("hide-editor-toolbar");
      }
      if (this._editContainer.value) {
        this._editContainer.value.appendChild(container);
      }
      this._editor && this.editorInitialized.emit(this._editor);
    }
  }
  async _closeEdit(destroyOnClose) {
    this._shouldClose = true;
    if (destroyOnClose && this._editor?.activeWorkflow) {
      if (this._editor.activeWorkflow?.activeWorkflow?.hasPendingEdits) {
        await this._editor.activeWorkflow.reset();
        await this._editor.cancelWorkflow();
      }
      this._editor.destroy();
    } else {
      if (this.graphicIndex > -1 && this.graphics?.length > 0) {
        this.refreshGraphics.emit(this.graphics);
      }
    }
    if (this.enableSnapping) {
      (this.mapView?.ui.view).grid = null;
    }
    this._shouldClose = false;
    this.closeEdit.emit();
  }
  async _startUpdate() {
    if (this.allowMultipleEditing) {
      await this._editor?.startUpdateFeaturesWorkflow(this.graphics);
    } else {
      await this._editor?.startUpdateWorkflowAtFeatureEdit(this.graphics[this.graphicIndex]);
    }
    this._shouldClose = true;
  }
}
customElement("edit-card", EditCard);
export {
  EditCard
};
