/* COPYRIGHT Esri - https://js.arcgis.com/1.2/LICENSE.txt */
import { c as customElement } from "../../chunks/runtime.js";
import { u as useT9n } from "../../chunks/useT9n.js";
import { css, html } from "lit";
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;
}

/* Override to hide Editor settings panel collapsible */
.hide-editor-toolbar .esri-editor__panel-toolbar {
  display: none !important;
}

.display-none {
  display: none !important;
}

/* override the padding of the feature form */
.esri-editor__panel-content {
  padding-block: 10px !important;
}

.notice-msg {
  padding: 10px;
  width: calc(100% - 20px);
}
}`;
class CreateRelatedFeature extends LitElement {
  constructor() {
    super(...arguments);
    this.customizeSubmit = false;
    this.enableSnapping = false;
    this.showGuidingMsg = true;
    this._editorLoading = false;
    this._translations = useT9n({ name: "create-related-feature", blocking: true });
    this._addingAttachment = false;
    this._isSubmitBtnClicked = false;
    this.success = createEvent();
    this.fail = createEvent();
    this.isActionPending = createEvent();
    this.formReady = createEvent();
  }
  static {
    this.properties = { customizeSubmit: [5, {}, { type: Boolean }], enableSnapping: [5, {}, { type: Boolean }], mapView: [0, {}, { attribute: false }], selectedFeature: [0, {}, { attribute: false }], showGuidingMsg: [5, {}, { type: Boolean }], table: [0, {}, { attribute: false }], _editorLoading: [16, {}, { state: true }], _translations: [16, {}, { state: true }] };
  }
  static {
    this.styles = styles;
  }
  static {
    this.shadowRootOptions = noShadowRoot;
  }
  willUpdate(changes) {
    if (changes.has("mapView")) {
      void this.mapViewWatchHandler();
    }
    if (changes.has("_editorLoading") && (this.hasUpdated || this._editorLoading !== false)) {
      void this._editorLoadingWatchHandler(this._editorLoading);
    }
  }
  async mapViewWatchHandler() {
    await this.mapView?.when(async () => {
      await this.init();
    });
  }
  async _editorLoadingWatchHandler(v) {
    if (v) {
      this._container?.classList.add("display-none");
      await this.startCreate();
      this._container?.classList.remove("display-none");
      this._editorLoading = false;
    }
  }
  async submit() {
    if (this._editor?.viewModel?.featureFormViewModel) {
      this._isSubmitBtnClicked = true;
      this._editor.viewModel.featureFormViewModel.submit();
    }
  }
  async init() {
    if (this.mapView) {
      await this.createEditorWidget();
    }
  }
  render() {
    const loaderClass = this._editorLoading ? "" : "display-none";
    return html`${this.showGuidingMsg && html`<calcite-notice class="notice-msg" icon=lightbulb kind=success open><div slot=message>${this._translations.provideDetailsMsg}</div></calcite-notice>` || ""}<calcite-loader class=${safeClassMap(loaderClass)} label scale=s></calcite-loader>`;
  }
  loaded() {
    void this.init();
  }
  disconnectedCallback() {
    super.disconnectedCallback();
    if (this._editor) {
      this._editor.destroy();
    }
  }
  async createEditorWidget() {
    if (this._editor) {
      this._editor.destroy();
    }
    this._container = document.createElement("div");
    this._container?.classList.add("display-none");
    if (!this.enableSnapping) {
      this._container.classList.add("hide-editor-toolbar");
    }
    this._editor = new Editor({
      view: this.mapView,
      visibleElements: {
        flow: true,
        settingsMenu: this.enableSnapping,
        sketch: false,
        snappingControls: this.enableSnapping
      },
      container: this._container
    });
    this.el.appendChild(this._container);
    const handle = reactiveUtils.watch(() => this._editor?.viewModel.featureTemplatesViewModel.state, (state) => {
      if (state === "ready") {
        this._editorLoading = true;
      }
    });
    this._editor?.viewModel.addHandles(handle);
    const attachmentHandle = reactiveUtils.watch(() => this._editor?.viewModel.state, (state) => {
      if (state === "adding-attachment" || state === "editing-attachment") {
        this._addingAttachment = true;
        this.isActionPending.emit(true);
      } else {
        if (this._addingAttachment) {
          this.isActionPending.emit(false);
          this._addingAttachment = false;
        }
      }
    });
    this._editor?.viewModel.addHandles(attachmentHandle);
    const formHandle = reactiveUtils.watch(() => this._editor?.viewModel.featureFormViewModel?.state, (state) => {
      if (state === "ready") {
        this.formReady.emit();
      }
    });
    this._editor?.viewModel.addHandles(formHandle);
  }
  async startCreate() {
    const parentLayer = this.selectedFeature?.layer;
    const childTable = this.table;
    if (parentLayer?.relationships && childTable?.relationships && this.selectedFeature && childTable.templates) {
      const parentRelationship = parentLayer.relationships[0];
      const childRelationship = childTable.relationships.find((rel) => parentLayer.layerId === rel.relatedTableId);
      const oid = Number(this.selectedFeature.getObjectId());
      if (!Number.isNaN(oid) && childRelationship) {
        const queryResult = await parentLayer.queryFeatures({
          objectIds: [oid],
          outFields: [parentLayer.objectIdField, parentRelationship.keyField]
        });
        const parentFeature = queryResult.features[0];
        const template = childTable.templates[0];
        const attributeOverrides = this.makeAttributesForRelatedFeature(parentFeature, parentRelationship, childRelationship);
        const creationInfo = {
          attributeOverrides,
          layer: childTable,
          template
        };
        await this._editor?.startCreateFeaturesWorkflowAtFeatureCreation(creationInfo);
        await this.hideEditorsElements();
        this._editor?.viewModel?.featureFormViewModel?.addHandles(this._editor.viewModel.featureFormViewModel.on("submit", this.submitted.bind(this)));
      }
    }
  }
  async hideEditorsElements() {
    if (!this.customizeSubmit) {
      return;
    }
    await this.timeout(700);
    this.el.querySelector(".esri-editor")?.querySelectorAll("calcite-flow-item")?.forEach((flowItem) => {
      const article = flowItem.shadowRoot?.querySelector("calcite-panel")?.shadowRoot?.querySelector("article");
      article?.querySelector("header")?.setAttribute("style", "display: none");
      article?.querySelector("footer")?.setAttribute("style", "display: none");
    });
  }
  makeAttributesForRelatedFeature(parentFeature, parentRelationship, childRelationship) {
    const parentKeyField = parentRelationship.keyField;
    let parentKeyValue;
    if (parentFeature.attributes.hasOwnProperty(parentKeyField)) {
      parentKeyValue = parentFeature.getAttribute(parentKeyField);
    } else if (parentFeature.attributes.hasOwnProperty(parentKeyField.toLowerCase())) {
      parentKeyValue = parentFeature.getAttribute(parentKeyField.toLowerCase());
    } else if (parentFeature.attributes.hasOwnProperty(parentKeyField.toUpperCase())) {
      parentKeyValue = parentFeature.getAttribute(parentKeyField.toUpperCase());
    }
    let childKeyField = childRelationship.keyField;
    const field = this.table?.fields.find((field2) => field2.name.toLocaleLowerCase() === childKeyField.toLocaleLowerCase());
    if (field) {
      childKeyField = field.name;
      const childAttributes = {
        [childKeyField]: parentKeyValue
      };
      return childAttributes;
    } else {
      return void 0;
    }
  }
  async submitted(_evt) {
    if (_evt.invalid.length) {
      this._isSubmitBtnClicked = false;
      return;
    }
    if (_evt.valid.length && this._isSubmitBtnClicked) {
      this._isSubmitBtnClicked = false;
      try {
        if (this._editor?.activeWorkflow) {
          await this._editor.activeWorkflow.commit();
          if (this._editor.viewModel.failures?.length) {
            this._editor.viewModel.failures.some((failure) => {
              if (failure.error) {
                throw failure.error;
              }
            });
          }
        }
      } catch (e) {
        this.fail.emit(e);
        return;
      }
      this.success.emit();
    }
  }
  async timeout(delay) {
    return new Promise((resolve) => setTimeout(resolve, delay));
  }
}
customElement("create-related-feature", CreateRelatedFeature);
export {
  CreateRelatedFeature
};
