/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
import { c as m } from "../../chunks/runtime.js";
import { css as f, html as d } from "lit";
import { u as p } from "../../chunks/useT9n.js";
import { LitElement as b, createEvent as n, noShadowRoot as g, safeClassMap as w } from "@arcgis/lumina";
import { createRef as y, ref as _ } from "lit-html/directives/ref.js";
import * as h from "@arcgis/core/core/reactiveUtils.js";
const v = f`@layer{:host{display:block}.hide-editor-toolbar .esri-editor__panel-toolbar,.display-none{display:none!important}.esri-editor__panel-content{padding-block:10px!important}.notice-msg{padding:10px;width:calc(100% - 20px)}}`;
class k extends b {
  constructor() {
    super(...arguments), this.customizeSubmit = !1, this.enableSnapping = !1, this.showGuidingMsg = !0, this._editorLoading = !1, this._translations = p({ name: "create-related-feature", blocking: !0 }), this._addingAttachment = !1, this._editor = y(), this._isSubmitBtnClicked = !1, this.success = n(), this.fail = n(), this.isActionPending = n(), this.formReady = n(), this._onEditorPropertyChange = () => {
      const e = this._editor.value;
      e && (h.watch(() => e.state, (t) => {
        t === "adding-attachment" || t === "editing-attachment" ? (this._addingAttachment = !0, this.isActionPending.emit(!0)) : this._addingAttachment && (this.isActionPending.emit(!1), this._addingAttachment = !1);
      }), h.watch(() => e.activeWorkflow?.formViewModel?.state, (t) => {
        t === "ready" && this.formReady.emit();
      }));
    };
  }
  static {
    this.properties = { customizeSubmit: 5, enableSnapping: 5, mapView: 0, selectedFeature: 0, showGuidingMsg: 5, table: 0, _editorLoading: 16, _translations: 16 };
  }
  static {
    this.styles = v;
  }
  static {
    this.shadowRootOptions = g;
  }
  async submit() {
    this._editor.value?.activeWorkflow && (this._isSubmitBtnClicked = !0, this._editor.value.activeWorkflow?.formViewModel?.submit());
  }
  render() {
    const e = this._editorLoading ? "" : "display-none";
    return d`${this.showGuidingMsg && d`<calcite-notice class="notice-msg" icon=lightbulb kind=success open><div slot=message>${this._translations.provideDetailsMsg}</div></calcite-notice>` || ""}<calcite-loader class=${w(e)} .label=${this._translations.loading} scale=s></calcite-loader>${this.mapView && this._getEditor() || ""}`;
  }
  disconnectedCallback() {
    super.disconnectedCallback(), this._editor.value && this._editor.value.destroy();
  }
  _getEditor() {
    return d`<arcgis-editor .view=${this.mapView} hide-edit-features-section .hideSettingsMenu=${!this.enableSnapping} hide-sketch .hideSnappingControlsElementsEnabledToggle=${!this.enableSnapping} @arcgisReady=${this._startCreate} @arcgisPropertyChange=${this._onEditorPropertyChange} ${_(this._editor)}></arcgis-editor>`;
  }
  async _startCreate() {
    const e = this.selectedFeature?.layer, t = this.table;
    if (e.relationships && t?.relationships && this.selectedFeature && t.templates) {
      const i = e.relationships[0], s = t.relationships.find((o) => e.layerId === o.relatedTableId), a = Number(this.selectedFeature.getObjectId());
      if (!Number.isNaN(a) && s) {
        const r = (await e.queryFeatures({
          objectIds: [a],
          outFields: [e.objectIdField, i.keyField]
        })).features[0], l = t.templates[0], u = {
          attributeOverrides: this.makeAttributesForRelatedFeature(r, i, s),
          layer: t,
          template: l
        };
        await this._editor.value?.startCreateFeaturesWorkflowAtFeatureCreation(u), await this.hideEditorsElements();
        const c = this._editor.value?.activeWorkflow?.formViewModel;
        c && this._editor.value?.activeWorkflow?.formViewModel?.addHandles(c.on("submit", this.submitted.bind(this)));
      }
    }
  }
  async hideEditorsElements() {
    if (!this.customizeSubmit)
      return;
    await this.timeout(700), this.el.querySelector("arcgis-editor")?.shadowRoot?.querySelectorAll("calcite-flow-item")?.forEach((t) => {
      const i = t.shadowRoot?.querySelector("calcite-panel")?.shadowRoot?.querySelector("article");
      i?.querySelector("header")?.setAttribute("style", "display: none"), i?.querySelector("footer")?.setAttribute("style", "display: none");
    });
  }
  makeAttributesForRelatedFeature(e, t, i) {
    const s = t.keyField;
    let a;
    e.attributes.hasOwnProperty(s) ? a = e.getAttribute(s) : e.attributes.hasOwnProperty(s.toLowerCase()) ? a = e.getAttribute(s.toLowerCase()) : e.attributes.hasOwnProperty(s.toUpperCase()) && (a = e.getAttribute(s.toUpperCase()));
    let o = i.keyField;
    const r = this.table?.fields.find((l) => l.name.toLocaleLowerCase() === o.toLocaleLowerCase());
    if (r)
      return o = r.name, {
        [o]: a
      };
  }
  async submitted(e) {
    if (e.invalid.length) {
      this._isSubmitBtnClicked = !1;
      return;
    }
    if (e.valid.length && this._isSubmitBtnClicked) {
      this._isSubmitBtnClicked = !1;
      try {
        if (this._editor.value?.activeWorkflow) {
          await this._editor.value.activeWorkflow.commit();
          const t = this._editor.value.activeWorkflow.failures;
          t?.length && t.some((i) => {
            if (i.error)
              throw i.error;
          });
        }
      } catch (t) {
        this.fail.emit(t);
        return;
      }
      this.success.emit();
    }
  }
  async timeout(e) {
    return await new Promise((t) => setTimeout(t, e));
  }
}
m("create-related-feature", k);
export {
  k as CreateRelatedFeature
};
