/* COPYRIGHT Esri - https://js.arcgis.com/5.0/LICENSE.txt */
import { c as u } from "../../chunks/runtime.js";
import { u as m } from "../../chunks/useT9n.js";
import { css as p, html as c } from "lit";
import { LitElement as f, createEvent as n, noShadowRoot as w, safeClassMap as b } from "@arcgis/lumina";
import y from "@arcgis/core/widgets/Editor";
import * as l from "@arcgis/core/core/reactiveUtils";
const _ = p`@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 g extends f {
  constructor() {
    super(...arguments), this.customizeSubmit = !1, this.enableSnapping = !1, this.showGuidingMsg = !0, this._editorLoading = !1, this._translations = m({ name: "create-related-feature", blocking: !0 }), this._addingAttachment = !1, this._isSubmitBtnClicked = !1, this.success = n(), this.fail = n(), this.isActionPending = n(), this.formReady = n();
  }
  static {
    this.properties = { customizeSubmit: 5, enableSnapping: 5, mapView: 0, selectedFeature: 0, showGuidingMsg: 5, table: 0, _editorLoading: 16, _translations: 16 };
  }
  static {
    this.styles = _;
  }
  static {
    this.shadowRootOptions = w;
  }
  willUpdate(e) {
    e.has("mapView") && this.mapViewWatchHandler(), e.has("_editorLoading") && (this.hasUpdated || this._editorLoading !== !1) && this._editorLoadingWatchHandler(this._editorLoading);
  }
  async mapViewWatchHandler() {
    await this.mapView?.when(async () => {
      await this.init();
    });
  }
  async _editorLoadingWatchHandler(e) {
    e && (this._container?.classList.add("display-none"), await this.startCreate(), this._container?.classList.remove("display-none"), this._editorLoading = !1);
  }
  async submit() {
    this._editor?.viewModel?.featureFormViewModel && (this._isSubmitBtnClicked = !0, this._editor.viewModel.featureFormViewModel.submit());
  }
  async init() {
    this.mapView && await this.createEditorWidget();
  }
  render() {
    const e = this._editorLoading ? "" : "display-none";
    return c`${this.showGuidingMsg && c`<calcite-notice class="notice-msg" icon=lightbulb kind=success open><div slot=message>${this._translations.provideDetailsMsg}</div></calcite-notice>` || ""}<calcite-loader class=${b(e)} label scale=s></calcite-loader>`;
  }
  loaded() {
    this.init();
  }
  disconnectedCallback() {
    super.disconnectedCallback(), this._editor && this._editor.destroy();
  }
  async createEditorWidget() {
    this._editor && this._editor.destroy(), this._container = document.createElement("div"), this._container?.classList.add("display-none"), this.enableSnapping || this._container.classList.add("hide-editor-toolbar"), this._editor = new y({
      view: this.mapView,
      visibleElements: {
        flow: !0,
        settingsMenu: this.enableSnapping,
        sketch: !1,
        snappingControls: this.enableSnapping
      },
      container: this._container
    }), this.el.appendChild(this._container);
    const e = l.watch(() => this._editor?.viewModel.featureTemplatesViewModel.state, (i) => {
      i === "ready" && (this._editorLoading = !0);
    });
    this._editor?.viewModel.addHandles(e);
    const t = l.watch(() => this._editor?.viewModel.state, (i) => {
      i === "adding-attachment" || i === "editing-attachment" ? (this._addingAttachment = !0, this.isActionPending.emit(!0)) : this._addingAttachment && (this.isActionPending.emit(!1), this._addingAttachment = !1);
    });
    this._editor?.viewModel.addHandles(t);
    const a = l.watch(() => this._editor?.viewModel.featureFormViewModel?.state, (i) => {
      i === "ready" && this.formReady.emit();
    });
    this._editor?.viewModel.addHandles(a);
  }
  async startCreate() {
    const e = this.selectedFeature?.layer, t = this.table;
    if (e?.relationships && t?.relationships && this.selectedFeature && t.templates) {
      const a = e.relationships[0], i = t.relationships.find((o) => e.layerId === o.relatedTableId), s = Number(this.selectedFeature.getObjectId());
      if (!Number.isNaN(s) && i) {
        const r = (await e.queryFeatures({
          objectIds: [s],
          outFields: [e.objectIdField, a.keyField]
        })).features[0], d = t.templates[0], h = {
          attributeOverrides: this.makeAttributesForRelatedFeature(r, a, i),
          layer: t,
          template: d
        };
        await this._editor?.startCreateFeaturesWorkflowAtFeatureCreation(h), await this.hideEditorsElements(), this._editor?.viewModel?.featureFormViewModel?.addHandles(this._editor.viewModel.featureFormViewModel.on("submit", this.submitted.bind(this)));
      }
    }
  }
  async hideEditorsElements() {
    this.customizeSubmit && (await this.timeout(700), this.el.querySelector(".esri-editor")?.querySelectorAll("calcite-flow-item")?.forEach((e) => {
      const t = e.shadowRoot?.querySelector("calcite-panel")?.shadowRoot?.querySelector("article");
      t?.querySelector("header")?.setAttribute("style", "display: none"), t?.querySelector("footer")?.setAttribute("style", "display: none");
    }));
  }
  makeAttributesForRelatedFeature(e, t, a) {
    const i = t.keyField;
    let s;
    e.attributes.hasOwnProperty(i) ? s = e.getAttribute(i) : e.attributes.hasOwnProperty(i.toLowerCase()) ? s = e.getAttribute(i.toLowerCase()) : e.attributes.hasOwnProperty(i.toUpperCase()) && (s = e.getAttribute(i.toUpperCase()));
    let o = a.keyField;
    const r = this.table?.fields.find((d) => d.name.toLocaleLowerCase() === o.toLocaleLowerCase());
    if (r)
      return o = r.name, {
        [o]: s
      };
  }
  async submitted(e) {
    if (e.invalid.length) {
      this._isSubmitBtnClicked = !1;
      return;
    }
    if (e.valid.length && this._isSubmitBtnClicked) {
      this._isSubmitBtnClicked = !1;
      try {
        this._editor?.activeWorkflow && (await this._editor.activeWorkflow.commit(), this._editor.viewModel.failures?.length && this._editor.viewModel.failures.some((t) => {
          if (t.error)
            throw t.error;
        }));
      } catch (t) {
        this.fail.emit(t);
        return;
      }
      this.success.emit();
    }
  }
  async timeout(e) {
    return new Promise((t) => setTimeout(t, e));
  }
}
u("create-related-feature", g);
export {
  g as CreateRelatedFeature
};
