/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
import { c as k } from "./runtime.js";
import { u as y } from "./useT9n.js";
import { LitElement as v, createEvent as h, nothing as S } from "@arcgis/lumina";
import { useContextConsumer as N } from "@arcgis/lumina/context";
import { css as R, html as l } from "lit";
import { createLongId as C, UserSession as $, getItemBase as O, getProp as D } from "@esri/solution-common";
import { C as E } from "./converter.js";
import { c as x } from "./deployAppContexts.js";
import { deploySolution as A } from "@esri/solution-deployer";
import { a as U, i as T, q as F } from "./helpers.js";
import { a as P, c as I } from "./validators.js";
import { createRef as u, ref as p } from "lit/directives/ref.js";
const V = R`*[tabindex]:focus-visible{outline:2px solid var(--calcite-color-brand);outline-offset:2px}.error-icon-color{--calcite-icon-color: var(--calcite-color-status-danger)}.outline{--calcite-block-border-color: var(--calcite-color-border-2);border:1px solid var(--calcite-color-border-input)}.space-around{margin:.5rem}.title-label{--calcite-label-margin-bottom: 1rem;font-weight:var(--calcite-font-weight-medium)}.padding-around{padding:1rem}.padding-top{padding-top:.5rem}.hidden{display:none}`, _ = "", m = "AzMGxyZ9AveCc5IZ", f = "dev", g = !1, b = "https://devext.arcgis.com", w = "9133940fea834c6fa8cd055d7e3d4802", j = {
  agoBasedEnterpriseSolutionsGroupId: _,
  appId: m,
  forceTrackingEnv: f,
  isEnterprise: g,
  portalURL: b,
  primarySolutionsGroupId: w
}, ee = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  agoBasedEnterpriseSolutionsGroupId: _,
  appId: m,
  default: j,
  forceTrackingEnv: f,
  isEnterprise: g,
  portalURL: b,
  primarySolutionsGroupId: w
}, Symbol.toStringTag, { value: "Module" }));
class M extends v {
  constructor() {
    super(...arguments), this.design = null, this.debugFailDeployment = !1, this.open = !1, this.userOptions = [], this._hasSpatialReferenceOption = !1, this._isFormValid = !1, this._isNameValid = !1, this._isSpatialReferenceOpen = !1, this._showAlertFailed = !1, this._showAlertNameErrorDescription = "", this._showAlertNameError = !1, this._solutionTitle = "", this._translations = y({ name: "solution-deploy-dialog", blocking: !0 }), this._wkid = "", this._wkidDescription = "", this._abortController = new AbortController(), this._configContextConsumer = N({
      context: x,
      subscribe: !0
    }), this._divNameErrorIcon = u(), this._divNameErrorMessage = u(), this._failedAlertRef = u(), this._customDeploymentMappings = {}, this._portalUrl = "", this._srPickerRef = void 0, this._tempUniqueTitle = "", this.deployCancelled = h(), this.deployFailed = h(), this.deployProgressEnd = h(), this.deployProgressStart = h(), this.deployProgressUpdated = h();
  }
  static {
    this.properties = { card: 0, design: 0, debugFailDeployment: 5, open: 5, userOptions: 0, _hasSpatialReferenceOption: 16, _isFormValid: 16, _isNameValid: 16, _isSpatialReferenceOpen: 16, _showAlertFailed: 16, _showAlertNameErrorDescription: 16, _showAlertNameError: 16, _solutionTitle: 16, _translations: 16, _wkid: 16, _wkidDescription: 16 };
  }
  static {
    this.styles = V;
  }
  close(e = !0) {
    this._isFormValid = !0, this._showAlertNameError = !1, this._showAlertFailed = !1, this._solutionTitle = this._tempUniqueTitle, this.open = !1, e && this.deployCancelled.emit();
  }
  closeAlert() {
    this._showAlertFailed = !1;
  }
  deploy() {
    this._showAlertFailed && this._failedAlertRef.value && (this._failedAlertRef.value.open = !1, this._showAlertFailed = !1), this.userOptions.forEach((t) => {
      t.props.forEach((o) => {
        o.prop === "wkid" && this._wkid !== "" && (o.value = this._wkid);
      });
    });
    const e = {
      jobId: C(),
      reuse: !1,
      card: this.card,
      userOptions: this.userOptions
    };
    this._configContextConsumer.value?.userSession && this._deploySolution(e, this._configContextConsumer.value.userSession);
  }
  async loaded() {
    if (this.card && (this._solutionTitle = this.card.title), this.userOptions.length > 0) {
      const t = this._checkUserOption("wkid");
      t && (this._hasSpatialReferenceOption = !0, t.default && this._srPickerRef && (this._wkidDescription = await this._srPickerRef?.getSRDescription()), this._wkid = t.default ?? "");
    }
    this._customDeploymentMappings = {}, this._portalUrl = this._configContextConsumer.value?.authentication?.PortalUrl || "";
    const e = U(this._portalUrl);
    this._anonAgolSession = new $({
      clientId: m,
      portal: `${e}/sharing/rest`
    }), window.enableDeployDebug = () => {
      this.debugFailDeployment = !0, console.log("✅ Deploy debug mode enabled - deployments will now fail for testing");
    }, window.disableDeployDebug = () => {
      this.debugFailDeployment = !1, console.log("✅ Deploy debug mode disabled - deployments will work normally");
    };
  }
  async willUpdate(e) {
    e.has("card") && (this._solutionTitle = this.card?.title ? this.card?.title : "", this._isFormValid = !0);
    const t = e.has("open") && this.open, o = e.has("card") && this.open;
    (t || o) && this._configContextConsumer.value?.authentication?.IsSignedIn && this._generateSolutionName(this._solutionTitle.trim()), (e.has("userOptions") || e.has("open")) && (await this._checkUserOptionState(), this._hasSpatialReferenceOption && this._wkid === "" && (this._isFormValid = !1));
  }
  render() {
    return this.open ? l`<calcite-dialog .heading=${this._translations.title.replace("{{solutionTitle}}", this.card?.title ?? "")} id=${this._translations.title.replace("{{solutionTitle}}", this.card?.title ?? "") ?? S} modal open outside-close-disabled @calciteDialogClose=${() => this.close()} width=m><div class="space-around">${this.renderUpdateSolutionName()}${this.renderSpatialReferenceSelection()}</div><calcite-button appearance=outline @click=${() => this.close()} slot=footer-end>${this._translations.cancel}</calcite-button>${this._isFormValid ? l`<calcite-button kind=brand @click=${this.deploy} slot=footer-end>${this._translations.deploy}</calcite-button>` : l`<calcite-button kind=brand slot=footer-end disabled>${this._translations.deploy}</calcite-button>`}<calcite-alert auto-close icon=exclamation-mark-triangle kind=danger .label=${this._translations.failedToDeploy.replace("{{solutionTitle}}", this.card.title)} @calciteAlertClose=${() => {
      this._showAlertFailed = !1;
    }} .open=${this._showAlertFailed} ${p(this._failedAlertRef)}><div slot=title>${this._translations.failedToDeploy.replace("{{solutionTitle}}", this.card.title)}</div></calcite-alert></calcite-dialog>` : "";
  }
  renderUpdateSolutionName() {
    return l`<div class="padding-around"><calcite-label scale=l class="title-label" tabindex=0>${this._translations.solutionName}</calcite-label><calcite-label scale=m><span tabindex=0>${this._translations.solutionNameHint}</span><calcite-input .label=${this._translations.solutionNameHint} max-length=250 @calciteInputInput=${async (e) => {
      const t = e.target.value.trim();
      this._isNameValid = await this._validateName(t), t === this._solutionTitle && (this._hasSpatialReferenceOption && this._wkid === "" ? this._isFormValid = !1 : (this._isFormValid = this._isNameValid, this._divNameErrorMessage.value && (this._isNameValid ? (this._divNameErrorMessage.value.innerHTML = "", this._divNameErrorIcon.value?.classList.add("hidden")) : (this._divNameErrorMessage.value.innerHTML = this._showAlertNameErrorDescription, this._divNameErrorIcon.value?.classList.remove("hidden")))));
    }} placeholder required scale=m .value=${this._solutionTitle.trim()}></calcite-input></calcite-label><calcite-label layout=inline><div class="hidden" ${p(this._divNameErrorIcon)}><calcite-icon aria-hidden=true class="error-icon-color" icon=exclamation-mark-triangle scale=s></calcite-icon></div><div ${p(this._divNameErrorMessage)}></div></calcite-label></div>`;
  }
  renderSpatialReferenceSelection() {
    return this._hasSpatialReferenceOption ? l`<div class="padding-around"><calcite-label scale=l class="title-label" tabindex=0>${this._translations.options}</calcite-label><calcite-block class="outline" .collapsible=${!!this._isSpatialReferenceOpen} .description=${this._wkid !== "" ? `${this._wkidDescription} [${this._wkid}]` : this._translations.spatialReferenceNoDefined} .expanded=${this._isSpatialReferenceOpen} .heading=${this._translations.spatialReference} @calciteBlockClose=${() => {
      this._isSpatialReferenceOpen = !1;
    }}>${!this._isSpatialReferenceOpen && this._wkid === "" && l`<calcite-button appearance=transparent kind=danger icon-start=exclamation-mark-triangle id=srs-alert-icon scale=l slot=content-end></calcite-button><calcite-tooltip reference-element=srs-alert-icon slot=content-end>${this._translations.selectSpatialReferenceNeeded}</calcite-tooltip>` || ""}${!this._isSpatialReferenceOpen && l`<calcite-button appearance=outline kind=brand @click=${() => {
      this._isSpatialReferenceOpen = !0;
    }} scale=m slot=content-end>${this._translations.modifyOption}</calcite-button>` || ""}<calcite-label layout=inline scale=s tabindex=0>${` ${this._translations.spatialReferenceInstructions} `}<a href=https://developers.arcgis.com/documentation/spatial-references/ target=_blank>${this._translations.spatialReferenceLearnMore}</a></calcite-label><arcgis-coordinate-system-picker .autoFilterToDefault=${this._wkid !== "" ? !0 : void 0} .defaultWkid=${this._wkid !== "" ? parseInt(this._wkid) : void 0} filter-enabled @arcgisChange=${async (e) => {
      e.detail?.latestWkid && this._srPickerRef && (this._wkidDescription = await this._srPickerRef.getSRDescription(), this._wkid = e.detail.latestWkid.toString(), this._isNameValid && (this._isFormValid = !0));
    }} ${p(async (e) => {
      if (this._srPickerRef = e, this._srPickerRef && !this._wkidDescription) {
        await this._srPickerRef.componentOnReady();
        const t = this._checkUserOption("wkid");
        t && t.default && (this._srPickerRef.value = {
          latestWkid: parseInt(t.default, 10)
        }, this._wkidDescription = await this._srPickerRef.getSRDescription() ?? "");
      }
    })}></arcgis-coordinate-system-picker>${this._wkid === "" && l`<calcite-label class="padding-top" layout=inline scale=s tabindex=0><calcite-icon aria-hidden=true class="error-icon-color" icon=exclamation-mark-triangle scale=s></calcite-icon>${this._translations.selectSpatialReferenceNeeded}</calcite-label>` || ""}</calcite-block></div>` : l`<div></div>`;
  }
  async _validateName(e) {
    this._solutionTitle = e, this._showAlertNameError = !1;
    const t = await P(e, this._configContextConsumer.value.userSession);
    if (!t.isValid) {
      switch (this._showAlertNameError = !0, t.errorType) {
        case "empty":
          this._showAlertNameErrorDescription = this._translations.solutionNameErrorBlank;
          break;
        case "exceed-length":
          this._showAlertNameErrorDescription = this._translations.solutionNameErrorLength;
          break;
        case "special-character":
          this._showAlertNameErrorDescription = this._translations.solutionNameErrorSpecialCharacter;
          break;
        case "not-unique":
          this._showAlertNameErrorDescription = this._translations.solutionNameErrorUniqueName.replace("{{proposedName}}", e);
          break;
      }
      return t.isValid;
    }
    return !0;
  }
  _simulateDeploymentFailure(e) {
    console.log("[DEBUG MODE] Simulating deployment failure..."), this.deployProgressStart.emit(this._abortController), this.deployProgressUpdated.emit({
      id: e.jobId,
      progress: 0
    }), setTimeout(() => {
      this.deployProgressUpdated.emit({
        id: e.jobId,
        progress: 25
      });
    }, 300), setTimeout(() => {
      this.deployProgressUpdated.emit({
        id: e.jobId,
        progress: 50
      });
    }, 600), setTimeout(() => {
      const t = new Error("DEBUG MODE: Simulated deployment failure for testing");
      this._showAlertFailed = !0, this.deployFailed.emit({
        card: e.card,
        jobId: e.jobId,
        error: t
      });
    }, 1500);
  }
  async _deploySolution(e, t) {
    const o = this._configContextConsumer.value.authentication;
    if (T(this._configContextConsumer.value)) {
      this.deployCancelled.emit();
      return;
    }
    if (this._abortController = new AbortController(), this.debugFailDeployment) {
      this._simulateDeploymentFailure(e);
      return;
    }
    const s = {
      progressCallback: (c, d) => {
        this.deployProgressUpdated.emit({
          id: d || "",
          progress: Math.round(c)
        });
      }
    };
    s.enableItemReuse = e.reuse, s.jobId = e.jobId, s.title = this._solutionTitle !== "" ? this._solutionTitle : this.card?.title;
    const i = await this._getUserParams(e), r = await this._getConvertedBuildSolutionParam();
    r && (i.buildSolution = r), s.templateDictionary = {
      params: i,
      workflowURL: o?.PortalSubset?.workflowURL || ""
    }, s.abortController = this._abortController, s.enableItemReuse = this.card?.supportReuse ?? !1;
    const a = this._configContextConsumer.value, n = a.agoBasedEnterpriseSolutionsGroupId && a.isEnterprise;
    s.storageAuthentication = n ? a.anonAgolSession : t || (this._anonAgolSession ?? void 0), this.deployProgressStart.emit(this._abortController), this.deployProgressUpdated.emit({
      id: e.jobId,
      progress: 0
    }), A(e.card.id, t, s).then((c) => {
      O(c, t).then((d) => {
        this.deployProgressUpdated.emit({
          id: e.card.id,
          progress: 100
        }), this.deployProgressEnd.emit(d.id);
      }, (d) => {
        console.error(d), this._showAlertFailed = !0, this.deployFailed.emit({
          card: e.card,
          jobId: s.jobId || "",
          error: d
        });
      });
    }, (c) => {
      console.error(c), this._showAlertFailed = !0, this.deployFailed.emit({
        card: e.card,
        jobId: s.jobId || "",
        error: c
      });
    });
  }
  async _getConvertedBuildSolutionParam() {
    if (!this.design)
      return null;
    try {
      const e = this.design?.sourceBuildSolution;
      return e ? new E({
        buildSolution: structuredClone(e)
      }).applyLlmTemplate(this.design)?.buildSolution ?? null : null;
    } catch (e) {
      return console.warn("Unable to build params.buildSolution from design; deploying with standard params only.", e), null;
    }
  }
  async _getUserParams(e) {
    const t = {}, o = D(e, "userOptions");
    if (o)
      for (const s of o)
        for (const i of s.props) {
          if (i.prop === "wkid") {
            const r = Number.parseInt(i.value, 10), a = this._configContextConsumer.value?.authentication?.Portal?.defaultExtent;
            if (a) {
              const n = await F(r, a);
              t.defaultExtent = n.toJSON();
            }
          }
          i.prop && (i.value !== "" ? i.valueType === "itemid" ? (t.useExisting = !0, t[i.prop] = {
            itemId: i.value,
            url: i.responseValue !== i.itemType ? i.responseValue : "",
            name: i.name,
            title: i.title,
            type: i.itemType,
            enterpriseIDMapping: this._customDeploymentMappings[i.prop] || {}
          }) : t[i.prop] = i.outType === "number" ? Number.parseInt(i.value, 10) : i.value : i.default !== "" && (t[i.prop] = i.default));
        }
    return t;
  }
  _checkUserOption(e) {
    for (const t of this.userOptions)
      for (const o of t.props)
        if (o.prop === e)
          return o;
    return null;
  }
  async _checkUserOptionState() {
    if (this.userOptions.length > 0) {
      this._hasSpatialReferenceOption = !1, this._wkid = "";
      const e = this._checkUserOption("wkid");
      e && (this._hasSpatialReferenceOption = !0, this._wkid = e.default ?? "");
    } else
      this._hasSpatialReferenceOption = !1, this._wkid = "", this._wkidDescription = "";
    this._wkid === "" ? this._isSpatialReferenceOpen = !0 : this._isSpatialReferenceOpen = !1;
  }
  async _generateSolutionName(e) {
    const t = await I(e, this._configContextConsumer.value.userSession), o = t.conflictingNames.length === 0, s = this._generateUniqueName(e, t.similiarNames);
    o ? this._tempUniqueTitle = s : (this._tempUniqueTitle = s, this._solutionTitle = s), this._isNameValid = !0;
  }
  _generateUniqueName(e, t) {
    const o = e.toLocaleLowerCase().replace(/[.*+?^${}()|[\]\\]/gu, "\\$&"), s = new RegExp(`^${o}(?: (\\d+))?$`, "iu"), i = t.map((a) => {
      const n = a.match(s);
      return n ? n[1] ? Number.parseInt(n[1], 10) : 0 : null;
    }).filter((a) => a !== null);
    if (!i.includes(0))
      return e;
    let r = 1;
    for (; i.includes(r); )
      r++;
    return `${e} ${r}`;
  }
}
k("solution-deploy-dialog", M);
export {
  M as S,
  ee as _
};
