/* COPYRIGHT Esri - https://js.arcgis.com/1.2/LICENSE.txt */
import { c as y } from "../../chunks/runtime.js";
import { a as v, g as _ } from "../../chunks/mapViewUtils.js";
import { u as M } from "../../chunks/useT9n.js";
import { css as b, html as d, nothing as I } from "lit";
import { createRef as p, ref as m } from "lit-html/directives/ref.js";
import { LitElement as L, createEvent as h, noShadowRoot as V, safeClassMap as u } from "@arcgis/lumina";
import { p as A } from "../../chunks/queryUtils.js";
import x from "@arcgis/core/widgets/Editor";
import k from "@arcgis/core/form/ExpressionInfo";
import S from "@arcgis/core/layers/FeatureLayer";
import E from "@arcgis/core/form/elements/FieldElement";
import F from "@arcgis/core/form/FormTemplate";
import P from "@arcgis/core/views/MapView";
import C from "@arcgis/core/widgets/Home";
import $ from "@arcgis/core/widgets/Search";
import * as g from "@arcgis/core/core/reactiveUtils";
import T from "@arcgis/core/request";
import * as R from "exifr";
import z from "@arcgis/core/geometry/Point";
import G from "@arcgis/core/geometry/SpatialReference";
const U = b`@layer{:host{display:block}.hide-editor-toolbar .esri-editor__panel-toolbar{display:none!important}.esri-editor__panel-content{padding-block:0px!important}.esri-editor .esri-item-list__group__header,.esri-editor__panel-content__section .esri-widget__heading{display:none!important}.esri-editor .esri-item-list__filter-container--sticky{padding-block:0px!important;padding-inline:10px!important}.search-widget{width:92%!important;margin:5px 14px 20px}.display-none{display:none!important}.hide-map{height:1%;visibility:hidden}.show-map{padding:10px!important;position:absolute!important;bottom:0;height:auto!important;width:calc(100% - 22px)}.notice-msg{padding:10px;width:calc(100% - 20px)}.edit-location-btn{margin:5px;display:flex}.esri-editor__panel-content{padding-block:10px!important}.esri-editor{height:auto!important}.content-container{padding:1.5rem}.instruction-text{margin-bottom:1.5rem;font-size:1rem}.selected-card{border:2px solid var(--calcite-ui-brand)}.upload-img-footer-container{width:100%;gap:5px;display:grid}.info-container{display:flex;align-items:center;gap:6px;margin-bottom:10px}.info-container calcite-icon{--calcite-icon-color: var(--calcite-color-brand)}.info-container span{font-size:12px;color:var(--calcite-ui-text-3)}.padding-10{padding:10px}.report-selection-container{display:flex;flex-direction:column;gap:12px;padding:10px;--calcite-card-border-color: var(--calcite-color-border-1)}.cursor-pointer{cursor:pointer}.card-body-content{display:flex;flex-direction:row;align-items:center;padding:16px;gap:24px}.text-stack{display:flex;flex-direction:column}.option-title{font-weight:var(--calcite-font-weight-bold);color:var(--calcite-ui-text-1);font-size:var(--calcite-font-size-0)}.option-description{color:var(--calcite-ui-text-3);font-size:var(--calcite-font-size--1)}.action-footer{display:flex;justify-content:center;margin-top:16px}.analysis-wrapper{display:flex;flex-direction:column;align-items:center;gap:5px;text-align:center;margin:auto}.analyzing-icon{--calcite-icon-color: var(--calcite-color-brand);animation:sparkle 2s infinite ease-in-out}@keyframes sparkle{0%,to{transform:scale(1)}50%{transform:scale(1.5)}}@media only screen and (max-width:600px){.esri-editor__panel-content{padding-block:0!important;min-height:0!important}}}`;
class H extends L {
  constructor() {
    super(...arguments), this.customizeSubmit = !1, this.enableSearch = !1, this.enableSnapping = !1, this.floorLevel = "", this.isMobile = !1, this.selectedLayerId = "", this.showGuidingMsg = !0, this.submitNewReportsMessage = "", this.updateMapPosition = !1, this.reportingArea = !1, this.reportingAreaLayer = "", this.reportingAreaMessage = "", this.showSketchWidgets = !1, this.allowMultipleCreation = !1, this.popupEnabled = !1, this.showLayerVisibilityMsg = !1, this.enablePhotoLocation = !1, this.aiImageExtraction = [], this._currentPage = "templatePicker", this._editorLoading = !1, this._inValidGeomtryDrawn = !1, this._selectedImageBase64 = "", this._imageAnalysisFailed = !1, this._translations = M({ name: "create-feature", blocking: !0 }), this._addingAttachment = !1, this._calciteNotice = p(), this._isSubmitBtnClicked = !1, this._mapViewContainer = p(), this._searchDiv = p(), this._inputImageForAI = p(), this._guidingMessageRefNode = p(), this._abortController = new AbortController(), this.success = h(), this.fail = h(), this.drawComplete = h(), this.editingLocation = h(), this.editingAttachment = h(), this.progressStatus = h(), this.modeChanged = h();
  }
  static {
    this.properties = { customizeSubmit: 5, enableSearch: 5, enableSnapping: 5, floorLevel: 1, formElements: 1, isMobile: 5, mapView: 0, searchConfiguration: 0, selectedLayerId: 1, showGuidingMsg: 5, submitNewReportsMessage: 1, updateMapPosition: 5, reportingArea: 5, reportingAreaLayer: 1, reportingAreaMessage: 1, showSketchWidgets: 5, allowMultipleCreation: 5, popupEnabled: 5, showLayerVisibilityMsg: 5, enablePhotoLocation: 5, aiImageExtraction: 0, _currentPage: 16, _editorLoading: 16, _inValidGeomtryDrawn: 16, _selectedImageBase64: 16, _imageAnalysisFailed: 16, _translations: 16 };
  }
  static {
    this.styles = U;
  }
  static {
    this.shadowRootOptions = V;
  }
  willUpdate(e) {
    e.has("mapView") && this.hasUpdated && this.mapViewWatchHandler(), e.has("isMobile") && this.hasUpdated && this.isMobileHandler(), e.has("_editorLoading") && (this.hasUpdated || this._editorLoading !== !1) && this._editorLoadingWatchHandler(this._editorLoading);
  }
  async mapViewWatchHandler() {
    this.mapView && await this.mapView.when(async () => {
      this._imageAnalysisInfo && !this._imageAnalysisInfo.canUseAI && await this.init();
    });
  }
  async isMobileHandler() {
    this.modeChanged.emit();
  }
  async _editorLoadingWatchHandler(e) {
    if (e) {
      if (this._container?.classList.add("display-none"), this._selectedLayer?.isTable) {
        if (this._selectedLayer.templates && this._editor) {
          const t = this._selectedLayer.templates[0], a = {
            layer: this._selectedLayer,
            template: t
          };
          await this._editor.startCreateFeaturesWorkflowAtFeatureCreation(a), await this.hideEditorsElements();
        }
      } else
        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 refresh(e) {
    this._editor && (e ? await this._setFloorLevel(e) : this.reportingArea && this.reportingAreaLayer && this._currentPage !== "drawing" ? await this.queryIntersectingFeatures() : this._currentPage !== "drawing" && (this._inValidGeomtryDrawn = !1, this.drawComplete.emit(this._inValidGeomtryDrawn)));
  }
  async showForm() {
    this.progressStatus.emit(100), this._container?.classList.remove("display-none"), this._mapViewContainer.value?.classList?.replace("show-map", "hide-map"), this._currentPage = "featureForm";
  }
  async load() {
    this._imageAnalysisInfo = await this._getImageAnalysisInfo(), this._currentPage = this._imageAnalysisInfo.canUseAI ? "chooseReportType" : "templatePicker";
  }
  async loaded() {
    this._imageAnalysisInfo && !this._imageAnalysisInfo.canUseAI && await this.init();
  }
  async updated() {
    if (this.isMobile && this.updateMapPosition) {
      const e = this._currentPage === "drawing" ? 80 : 30, t = this.enableSearch ? this._searchDiv.value?.offsetHeight : 0;
      await this._calciteNotice.value?.componentOnReady();
      const i = (this._calciteNotice.value?.offsetHeight || 0) + t + e;
      this._mapViewContainer.value && (this._mapViewContainer.value.style.top = `${i}px`);
    }
    this.reportingAreaMessage && this._guidingMessageRefNode.value?.children[0] && (this._guidingMessageRefNode.value.children[0].style.margin = "0px");
  }
  disconnectedCallback() {
    super.disconnectedCallback(), this._editor && (this._editor.viewModel.sketchViewModel && this._editor.viewModel.sketchViewModel?.destroy(), this._editor.destroy(), this.enableSnapping && this.mapView?.ui.view && ((this.mapView?.ui.view).grid = null));
  }
  render() {
    const e = this._currentPage === "drawing" || this._currentPage === "editing" ? "" : "display-none", t = this._editorLoading ? "" : "display-none", a = this._editorLoading ? "display-none" : "", i = this.isMobile && this.updateMapPosition ? "show-map" : "display-none", o = this._inValidGeomtryDrawn ? "danger" : "success", l = this._inValidGeomtryDrawn ? "exclamation-mark-triangle" : "lightbulb", s = this.showLayerVisibilityMsg && this._currentPage === "templatePicker", n = this.showGuidingMsg || s;
    let r = this._translations.chooseCategoryMsg;
    const c = this._imageAnalysisInfo?.canUseAI && ["chooseReportType", "analyzingImage", "imageUpload"].includes(this._currentPage);
    return this._inValidGeomtryDrawn ? r = this.reportingAreaMessage || this._translations.reportOutsideAreaMessage : this._currentPage === "drawing" || this._currentPage === "editing" ? r = this._translations.provideLocationMsg : this._currentPage === "featureForm" ? r = this._imageAnalysisInfo?.results?.length ? this._translations.formReviewMsg : this._translations.provideDetailsMsg : s && (r = this._translations.enableFeatureTemplatesMessage), d`${this._imageAnalysisFailed && d`<calcite-alert auto-close icon=x-octagon kind=danger label @calciteAlertClose=${() => {
      this._imageAnalysisFailed = !1;
    }} open placement=top><div slot=title>${this._translations.error}</div><div slot=message>${this._translations.imageExtractionError}</div></calcite-alert>` || ""}${c && d`<calcite-panel>${this._currentPage === "chooseReportType" && this._getReportTypePage() || ""}${this._currentPage === "imageUpload" && this._aiImageExtractionPage() || ""}${this._currentPage === "analyzingImage" && this._getAnalyzingImagePage() || ""}</calcite-panel>` || ""}${!c && d`${n && d`<calcite-notice class="notice-msg" .icon=${l} .kind=${o} open ${m(this._calciteNotice)}><div slot=message .innerHTML=${r ?? ""} ${m(this._guidingMessageRefNode)}></div></calcite-notice>` || ""}<calcite-loader class=${u(t)} label scale=s></calcite-loader>${this._currentPage === "featureForm" && this.isMobile && d`<calcite-button appearance=transparent class="edit-location-btn" icon-start=pin @click=${this.editLocation}>${this._translations.editLocationLabel}</calcite-button>` || ""}<div class=${u(a)} id=feature-form></div>${this.enableSearch && d`<div class=${`search-widget ${e} ${a}`} id=search-widget-ref ${m(this._searchDiv)}></div>` || ""}` || ""}<div class=${u(i)} ${m(this._mapViewContainer)}></div>`;
  }
  async init() {
    this.mapView && this.selectedLayerId && (this._updatedMapView = this.mapView, await (this.isMobile && this.updateMapPosition ? this.createMobileMapView() : this._loadWidgets()));
  }
  async createMobileMapView() {
    this._mapViewContainer.value && this.mapView && (this._mapViewContainer.value.classList.add("hide-map"), await new P({
      map: this.mapView.map,
      container: this._mapViewContainer.value,
      zoom: this.mapView.zoom,
      center: this.mapView.center,
      popupEnabled: this.popupEnabled
    }).when((e) => {
      this._updatedMapView = e;
      const t = new C({
        view: this._updatedMapView
      });
      t && this._updatedMapView.ui.add(t, "top-left"), this._loadWidgets();
    }, (e) => {
      console.log(e);
    }));
  }
  async _loadWidgets() {
    await this.createEditorWidget(), this.enableSearch && await this.createSearchWidget();
  }
  _getReportTypePage() {
    return d`<div class="report-selection-container"><calcite-label>${this._translations.createReportHeading}</calcite-label><calcite-card class="cursor-pointer" @click=${() => {
      this.progressStatus.emit(35), this._currentPage = "imageUpload";
    }}><div slot=description class="card-body-content"><calcite-icon icon=effects scale=l style="color: var(--calcite-ui-text-2)"></calcite-icon><div class="text-stack"><span class="option-title">${this._translations.aiImgExtractionLabel}</span><span class="option-description">${this._translations.aiAssistantDescription}</span></div></div></calcite-card><calcite-card class="cursor-pointer" @click=${() => {
      this._currentPage = "templatePicker", this.init();
    }}><div slot=description class="card-body-content"><calcite-icon icon=pencil scale=l></calcite-icon><div class="text-stack"><span class="option-title">${this._translations.fillOutManually}</span><span class="option-description">${this._translations.startBlank}</span></div></div></calcite-card></div>`;
  }
  _aiImageExtractionPage() {
    const e = this._selectedImageBase64 !== "", t = e ? this._translations.replaceImage : this._translations.imageUploadLimitHint;
    return d`<calcite-notice class="notice-msg" icon=effects kind=brand open><div slot=message>${this._translations.aiAssistantProcessingHint}</div></calcite-notice><div class="padding-10"><calcite-label><div>${this._translations.photo}<span style="color: var(--calcite-color-status-danger)">*</span></div><calcite-input type=file accept=image/* @calciteInputInput=${this._onImageUpload} ${m(this._inputImageForAI)}></calcite-input></calcite-label><div class="info-container"><calcite-icon icon=information scale=s></calcite-icon><span>${t}</span></div>${e && d`<img class="width-full" src=${this._selectedImageBase64 ?? I}>` || ""}</div><div slot=footer class="upload-img-footer-container"><calcite-button width=full .disabled=${!e} id=next-btn @click=${this._analyzeImage}>${this._translations.next}</calcite-button><calcite-button width=full appearance=outline kind=brand @click=${() => this.modeChanged.emit()}>${this._translations.cancel}</calcite-button></div>`;
  }
  _getAnalyzingImagePage() {
    return d`<div class="analysis-wrapper"><calcite-label layout=inline><calcite-icon class="analyzing-icon" icon=effects scale=s></calcite-icon><span>${this._translations.analyzingImage}</span></calcite-label><calcite-button class="skip-btn" appearance=transparent @click=${() => {
      this._abortController.abort(), this._currentPage = "templatePicker";
    }}>${this._translations.skip}</calcite-button></div>`;
  }
  _onImageUpload(e) {
    const t = e.target;
    if (t) {
      const a = t.files[0], i = new FileReader();
      i.onload = (o) => {
        this._selectedImageBase64 = o.target?.result;
      }, i.readAsDataURL(a);
    }
  }
  async _analyzeImage() {
    this._abortController = new AbortController();
    const e = this._abortController.signal, t = await this._getImageAnalysisInfo();
    if (!t.canUseAI || !t.url || !this._inputImageForAI.value?.files?.length) {
      this._imageAnalysisFailed = !0, console.error(this._translations.error), this._resetImageAnalysisInfo(), await this.init();
      return;
    }
    try {
      this._currentPage = "analyzingImage", this.progressStatus.emit(45);
      const a = this._inputImageForAI.value.files[0], i = await new Promise((s, n) => {
        const r = new FileReader();
        r.onloadend = () => s(r.result), r.onerror = n, this._inputImageForAI.value && r.readAsDataURL(a);
      }), o = await R.gps(a);
      if (o?.longitude && o.latitude && this.mapView?.spatialReference) {
        const s = new z({
          longitude: o.longitude,
          latitude: o.latitude,
          spatialReference: new G({ wkid: 4326 })
        }), n = await A(s, this.mapView.spatialReference);
        this._imageAnalysisInfo && (this._imageAnalysisInfo.imageLocation = n);
      }
      const l = [];
      if (this.aiImageExtraction.forEach((s) => {
        s?.field && s.prompt && s.id === this.selectedLayerId && l.push({ key: s.field, context: s.prompt });
      }), l.length) {
        const s = {
          input: i,
          data: l
        }, n = await T(t.url, {
          method: "post",
          headers: {
            "Content-Type": "application/json",
            "x-esri-authorization": `Bearer ${t.token}`
          },
          body: JSON.stringify(s),
          responseType: "json",
          signal: e
        });
        this._imageAnalysisInfo && (this._imageAnalysisInfo.results = n.data.results);
      }
      await this.init();
    } catch (a) {
      a.name === "AbortError" ? console.error("Aborted", a) : (this._imageAnalysisFailed = !0, console.error("Analyzing failed", a)), this._resetImageAnalysisInfo(), this.init();
    }
  }
  _resetImageAnalysisInfo() {
    const e = {
      url: "",
      token: "",
      canUseAI: !1,
      imageLocation: void 0,
      results: []
    };
    this._imageAnalysisInfo = e;
  }
  async _getImageAnalysisInfo() {
    const e = {
      url: "",
      token: "",
      canUseAI: !1
    };
    if (this.enablePhotoLocation) {
      const t = (this.mapView?.map).portalItem.portal;
      if (t) {
        const a = await t.fetchSettings(), i = t?.helperServices.aiUtilityServices;
        i?.url && i?.api?.image_analyze && (e.url = i.url + i.api.image_analyze), t.credential && (e.token = t.credential.token), a?.aiAssistantsEnabled && !a.blockBetaApps && t?.user?.privileges?.includes("portal:user:useAIAssistants") && (e.canUseAI = !0);
      }
    }
    return e;
  }
  async createEditorWidget() {
    this._editor && this._editor.destroy();
    const e = [];
    this._container = document.createElement("div"), this._container?.classList.add("display-none"), this.enableSnapping || this._container.classList.add("hide-editor-toolbar");
    const t = this._updatedMapView && await v(this._updatedMapView), a = this.mapView && await _(this.mapView, this.selectedLayerId);
    if (a && (this._selectedLayer = a, !this._selectedLayer?.isTable && t && t.forEach((i) => {
      e.push({
        layer: i,
        enabled: i?.type === "feature" && i?.id === this.selectedLayerId,
        addEnabled: !0,
        // default is true, set to false to disable the ability to add a new feature
        updateEnabled: !1,
        // if true, enable ability to edit an existing feature
        deleteEnabled: !1
        // default is true, set to false to disable the ability to delete features
      });
    })), this._editor = new x({
      view: this._updatedMapView,
      layerInfos: e,
      visibleElements: {
        settingsMenu: this.enableSnapping,
        snappingControls: this.enableSnapping,
        createFeaturesSection: !0,
        editFeaturesSection: !1,
        flow: !0,
        sketch: this.showSketchWidgets && this._selectedLayer?.geometryType !== "point"
      },
      container: this._container
    }), this._mapViewContainer.value ? this.el.insertBefore(this._container, this._mapViewContainer.value) : this.el.appendChild(this._container), this._selectedLayer?.isTable && (this._editorLoading = !0), this._editor) {
      const i = g.watch(() => this._editor?.viewModel.state, (r) => {
        r === "adding-attachment" || r === "editing-attachment" ? (this._addingAttachment = !0, this.editingAttachment.emit(!0)) : this._addingAttachment && (this.editingAttachment.emit(!1), this._addingAttachment = !1);
      });
      i && this._editor.viewModel.addHandles(i);
      const o = g?.watch(() => this._editor?.viewModel.featureTemplatesViewModel.state, (r) => {
        r === "ready" && this._editor?.viewModel?.activeWorkflow?.type !== "create-features" && (this.progressStatus.emit(50), this._editorLoading = !0);
      });
      o && this._editor.viewModel.addHandles(o);
      const l = g?.watch(() => this._editor?.viewModel.featureFormViewModel?.state, (r) => {
        r === "ready" && this._editor?.viewModel.featureFormViewModel && this._currentPage !== "editing" && (this._mapViewContainer.value?.classList?.replace("show-map", "hide-map"), this._editor.viewModel.featureFormViewModel.addHandles(this._editor.viewModel.featureFormViewModel.on("submit", this.submitted.bind(this))), setTimeout(() => {
          this._setFloorLevel(this.floorLevel);
        }, 50), !this.allowMultipleCreation && this._editor.activeWorkflow && (this._editor.activeWorkflow.data.creationInfo.maxFeatures = 1), this._currentPage = "featureForm", this._imageAnalysisInfo?.results && this._imageAnalysisInfo.results.forEach((c) => {
          this._editor?.viewModel.featureFormViewModel && c.key && this._editor.viewModel.featureFormViewModel.setValue(c.key, c.value);
        }), this.progressStatus.emit(100), this.drawComplete.emit(!1));
      });
      l && this._editor.viewModel.addHandles(l);
      const s = g.watch(() => this._editor?.viewModel.state, (r) => {
        r === "creating-features" && this._editor?.viewModel.featureFormViewModel && this._editor.viewModel.featureFormViewModel.state === "disabled" && (this._mapViewContainer.value?.classList.replace("hide-map", "show-map"), this._selectedLayer && !this._selectedLayer.isTable && (this._currentPage = "drawing", this._editor.viewModel.sketchViewModel?.createGraphic && this._imageAnalysisInfo?.imageLocation && (this._updatedMapView?.goTo({ center: this._imageAnalysisInfo.imageLocation }), this._selectedLayer.geometryType === "point" && this._initializeSketchPoint(this._imageAnalysisInfo.imageLocation.clone()))));
      });
      s && this._editor.viewModel.addHandles(s), this._editor.on("sketch-create", async (r) => {
        r.detail.state === "complete" && (this._drawnGeometry = r.detail.graphic?.geometry, this.reportingArea && this.reportingAreaLayer && await this.queryIntersectingFeatures());
      });
      let n;
      this._editor.on("sketch-update", (r) => {
        clearTimeout(n), n = window.setTimeout(async () => {
          this._drawnGeometry = r.detail.graphics[0].geometry, this.reportingArea && this.reportingAreaLayer && await this.queryIntersectingFeatures();
        }, 50);
      });
    }
  }
  async queryIntersectingFeatures() {
    const e = this.mapView && await _(this.mapView, this.reportingAreaLayer);
    if (e) {
      const t = e.createQuery();
      t.geometry = this._drawnGeometry, t.spatialRelationship = "intersects";
      const i = await e.queryFeatureCount(t) === 0;
      this._inValidGeomtryDrawn = i, this.drawComplete.emit(this._inValidGeomtryDrawn);
    }
  }
  editLocation() {
    this.progressStatus.emit(75), this.editingLocation.emit(), this._container?.classList.add("display-none"), this._mapViewContainer.value?.classList.replace("hide-map", "show-map"), this._currentPage = "editing";
  }
  async startCreate() {
    return await this.hideEditorsElements(), new Promise((e, t) => {
      if (this._editor?.viewModel.featureTemplatesViewModel.items?.length) {
        const a = this._editor.viewModel.featureTemplatesViewModel.items[0].items;
        this._editor.viewModel.featureTemplatesViewModel.addHandles(this._editor.viewModel.featureTemplatesViewModel.on("select", () => {
          this.progressStatus.emit(75), setTimeout(() => {
            this.hideEditorsElements().then(() => {
              e({});
            }, (o) => t(o));
          }, 700);
        })), a.length === 1 && this._editor.viewModel.featureTemplatesViewModel.select(a[0]);
        const i = a.length > 1;
        this.hideEditorsElements().then(() => {
          i && (this._currentPage = "templatePicker", e({}));
        }, (o) => i && t(o));
      }
    });
  }
  async createSearchWidget() {
    if (this._updatedMapView) {
      let e = {
        view: this._updatedMapView
      };
      if (this.searchConfiguration && (e = {
        ...this._getSearchConfig(this.searchConfiguration, this._updatedMapView)
      }), this._search = new $(e), !this._search)
        return;
      this._search.container = "search-widget-ref", this._search.popupEnabled = !1, this._search.resultGraphicEnabled = !1;
      let t;
      this._search.viewModel.addHandles(this._search.on("search-complete", (i) => {
        i.results[0].results && i.results[0].results[0] && (i.results[0].results[0].extent && this._updatedMapView?.goTo(i.results[0].results[0].extent), this._selectedLayer?.geometryType === "point" && (t = i.results[0].results[0]?.feature.geometry));
      }));
      const a = g.watch(() => this._search?.viewModel.state, (i) => {
        i === "ready" && setTimeout(() => {
          if (this._editor?.viewModel.sketchViewModel?.createGraphic && t)
            this._initializeSketchPoint(t);
          else if (this._editor?.viewModel.sketchViewModel && this._editor.viewModel.sketchViewModel.updateGraphics.length > 0 && t) {
            const o = this._editor?.viewModel.sketchViewModel?.updateGraphics.getItemAt(0);
            o && (o.set("geometry", t), this._editor?.viewModel.sketchViewModel?.update(o), this.hideEditorsElements());
          }
        }, 100);
      });
      a && this._search.viewModel.addHandles(a);
    }
  }
  async _initializeSketchPoint(e) {
    if (this._editor?.viewModel.sketchViewModel?.createGraphic) {
      const t = e.clone(), i = this._editor.viewModel.sketchViewModel.createGraphic.set("geometry", e).clone();
      this._editor.viewModel.sketchViewModel.addGraphic(i), this._editor.viewModel.sketchViewModel.emit("create", {
        graphic: i,
        state: "complete",
        toolEventInfo: null,
        type: "create"
      }), await this._editor.viewModel.sketchViewModel.update(t), this.hideEditorsElements();
    }
  }
  _getSearchConfig(e, t) {
    const a = "includeDefaultSources", i = e.sources;
    return i && i?.length > 0 ? (e[a] = !1, i.forEach((o) => {
      if (o.hasOwnProperty("layer")) {
        const s = o, n = s.layer?.id, r = n ? t.map?.findLayerById(n) : "", c = s?.layer?.url;
        r ? s.layer = r : c && (s.layer = new S(c));
      }
    }), i?.forEach((o) => {
      if (o.hasOwnProperty("locator")) {
        const s = o;
        if (s?.name === "ArcGIS World Geocoding Service") {
          const n = s.outFields || ["Addr_type", "Match_addr", "StAddr", "City"];
          s.outFields = n, s.singleLineFieldName = "SingleLine";
        }
        s.url = s.url, delete s.url;
      }
    })) : e = {
      ...e,
      includeDefaultSources: !0
    }, e;
  }
  async _setFloorLevel(e) {
    if (!e)
      return;
    const t = this._selectedLayer, a = t?.floorInfo?.floorField;
    if (a) {
      const i = t.fields.find((o) => o.name === a);
      if (i && !t?.formTemplate)
        this._editor?.viewModel.featureFormViewModel && (this._editor.viewModel.featureFormViewModel.setValue(i.name, e), i.editable = !1);
      else if (t.formTemplate && this.formElements) {
        const o = new k({
          expression: `'${e}'`,
          name: "floor-info-test",
          title: "Floor Info",
          returnType: "string"
        }), l = new E({
          label: a,
          editableExpression: "false",
          fieldName: a,
          input: {
            type: "text-box",
            maxLength: 50,
            minLength: 0
          },
          valueExpression: o.name
        });
        this._updatedMapView?.map.editableLayers.forEach((s) => {
          const n = this.formElements.orgElements, r = this.formElements.orgExpressionInfos, c = [...n];
          if (c.push(l), s.type === "feature") {
            const f = s, w = new F({
              title: f?.formTemplate?.title,
              description: f?.formTemplate?.description,
              elements: c,
              expressionInfos: [o].concat(r)
            });
            s.formTemplate = w;
          }
        });
      }
    }
  }
  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");
    }));
  }
  async submitted(e) {
    if (e.invalid.length) {
      this._isSubmitBtnClicked = !1;
      return;
    }
    if (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));
  }
}
y("create-feature", H);
export {
  H as CreateFeature
};
