/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
import { c as v } from "../../chunks/runtime.js";
import { u as T } from "../../chunks/useT9n.js";
import { LitElement as D, createEvent as m, safeClassMap as u } from "@arcgis/lumina";
import { useContextConsumer as $ } from "@arcgis/lumina/context";
import { css as P, html as h } from "lit";
import { I as b, T as V } from "../../chunks/interfaces.js";
import { createRef as _, ref as p } from "lit-html/directives/ref.js";
import { c as w } from "../../chunks/deployAppContexts.js";
import * as E from "@esri/solution-common";
import { updateGroup as x, updateItem as g, updateItemExtended as W } from "@esri/solution-common";
import { v as C } from "../../chunks/validators.js";
import { g as L } from "../../chunks/getRelatedInfos.js";
import { h as N, i as y, j as O } from "../../chunks/helpers.js";
const R = P`*[tabindex]:focus-visible{outline-style:solid!important;outline-width:2px!important;outline-color:var(--calcite-color-brand)!important;outline-offset:2px!important}.display-flex{display:flex}.display-none{display:none}.flex-direction-column{flex-direction:column}.flex-direction-row{flex-direction:row}.font-weight-medium{font-weight:var(--calcite-font-weight-medium)}.font-style-1{font-size:1rem;color:var(--calcite-color-text-2)}.margin-top-0{margin-top:0}.padding-top-20{padding-top:20px}.padding-bottom-2{padding-bottom:2rem}.padding-left-2{padding-left:2rem}.padding-right-2{padding-right:2rem}.padding-end-1{padding-inline-end:1rem}.padding-end-1-2{padding-inline-end:.5rem}.width-full{width:100%}.justify-content-space{justify-content:space-between}`;
class k extends D {
  constructor() {
    super(...arguments), this.open = !1, this.source = "Card Dropdown", this.solutionData = {}, this.templateInfos = [], this._saveDisabled = !1, this._displayTemplateInfos = [], this._hasNameLengthError = !1, this._nonSolutionDependencyItems = [], this._solutionItemsTitlesUpdating = !1, this._translations = T({ name: "solution-configure-titles", blocking: !0 }), this._configContextConsumer = $({
      context: w,
      subscribe: !0
    }), this._defaultPrefix = "", this._defaultSuffix = "", this._loadingDefaultPrefix = !1, this._loadingDefaultSuffix = !1, this._prefixRef = _(), this._prefixValue = "", this._suffixRef = _(), this._suffixValue = "", this._templateInfos = [], this._originalTitles = [], this.solutionConfigureTitlesBeforeClose = m(), this.solutionItemsTitlesChanged = m();
  }
  static {
    this.properties = { card: 0, open: 5, source: 1, solutionData: 1, templateInfos: 0, _saveDisabled: 16, _displayTemplateInfos: 16, _hasNameLengthError: 16, _nonSolutionDependencyItems: 16, _solutionItemsTitlesUpdating: 16, _translations: 16 };
  }
  static {
    this.styles = R;
  }
  async willUpdate(e) {
    if (e.has("templateInfos") && (this._templateInfos = JSON.parse(JSON.stringify(this.templateInfos)), this._updateTemplates()), e.has("open")) {
      const i = e.get("open");
      if (this.open && !i) {
        await this._updatePrefixSuffix(), this._templateInfos = JSON.parse(JSON.stringify(this.templateInfos)), this._originalTitles = this._templateInfos.map((t) => ({ id: t.id, title: t.title })), this._updateTemplates();
        const a = await L(this._configContextConsumer.value.userSession, this.card);
        this._nonSolutionDependencyItems = a._nonSolutionDependencyItems, await this._accordionRef?.expandFirstItem();
      }
    }
  }
  get _telemetry() {
    return this._configContextConsumer.value?.telemetrySession;
  }
  async load() {
    this._updateTemplates(), await this._updatePrefixSuffix();
  }
  async _updatePrefixSuffix() {
    this.solutionData = await E.getItemDataAsJson(this.card.id, this._configContextConsumer.value.userSession), this.solutionData.titles?.prefix && (this._loadingDefaultPrefix = !0, this._defaultPrefix = this.solutionData.titles.prefix, this._prefixValue = this.solutionData.titles.prefix), this.solutionData.titles?.suffix && (this._loadingDefaultSuffix = !0, this._defaultSuffix = this.solutionData.titles.suffix, this._suffixValue = this.solutionData.titles.suffix);
  }
  render() {
    return h`<calcite-dialog .heading=${this.card.title} modal @calciteDialogBeforeClose=${() => {
      this.solutionConfigureTitlesBeforeClose.emit();
    }} .open=${this.open} outside-close-disabled width=l>${this._getPrefixSuffixControls()}${this._getAccordion()}${this._getDialogButtons()}</calcite-dialog>`;
  }
  _getPrefixSuffixControls() {
    const e = C(this._prefixValue), i = this._hasNameLengthError && this._prefixValue.length > 0, a = e.errorType !== "special-character", t = !i, s = a ? "display-none" : "", n = t ? "display-none" : "", d = a && t ? "valid" : "invalid", c = C(this._suffixValue), l = this._hasNameLengthError && this._suffixValue.length > 0, o = c.errorType !== "special-character", r = !l, f = o ? "display-none" : "", I = r ? "display-none" : "", S = o && r ? "valid" : "invalid";
    return this._saveDisabled = !a || !t || !o || !r || !this._hasChanges(), h`<div class="display-flex flex-direction-column padding-left-2 padding-right-2 padding-top-20"><calcite-label scale=l class="font-weight-medium"><span tabindex=0>${this._translations.configureTitlesDialogHeader}</span></calcite-label><p class="font-style-1 margin-top-0" tabindex=0>${this._translations.addPrefixOrSuffixToItems}</p><div class="display-flex flex-direction-row justify-content-space"><calcite-label class="width-full padding-end-1" scale=l>${this._translations.prefixToAddToItems}<calcite-input clearable @blur=${this._prefixInput} @input=${this._prefixInput} .placeholder=${this._translations.enterPrefixPlaceholder} .status=${d} .value=${this._prefixValue} ${p(this._prefixRef)}></calcite-input><calcite-input-message class=${u(s)} icon=exclamation-mark-triangle status=invalid>${this._translations.invalidPrefixOrSuffixCharsError}</calcite-input-message><calcite-input-message class=${u(n)} icon=exclamation-mark-triangle status=invalid>${this._translations.invalidPrefixOrSuffixLengthError}</calcite-input-message></calcite-label><calcite-label class="width-full" scale=l>${this._translations.suffixToAddToItems}<calcite-input clearable @blur=${this._suffixInput} @input=${this._suffixInput} .placeholder=${this._translations.enterSuffixPlaceholder} .status=${S} .value=${this._suffixValue} ${p(this._suffixRef)}></calcite-input><calcite-input-message class=${u(f)} icon=exclamation-mark-triangle status=invalid>${this._translations.invalidPrefixOrSuffixCharsError}</calcite-input-message><calcite-input-message class=${u(I)} icon=exclamation-mark-triangle status=invalid>${this._translations.invalidPrefixOrSuffixLengthError}</calcite-input-message></calcite-label></div></div>`;
  }
  _getAccordion() {
    const e = N(this._nonSolutionDependencyItems, this.card.id);
    return h`<div class="display-flex flex-direction-column padding-left-2 padding-right-2 padding-bottom-2"><p class="font-style-1 margin-top-0">${this._translations.previewTheChanges}</p><solution-item-accordion .itemRelationshipDependencies=${e} list-selection-mode=multiple .reuseWarning=${this._translations.itemDependencyReuseWarning} .templateInfos=${this._displayTemplateInfos} .typeKeywords=${this.card?.typeKeywords} usage-context=rename ${p(async (i) => {
      i && (this._accordionRef = i);
    })}></solution-item-accordion></div>`;
  }
  _getDialogButtons() {
    return h`<div slot=footer-end><calcite-button appearance=outline class="padding-end-1-2" kind=brand @click=${this._closeDialog}>${this._translations.cancelTheDialog}</calcite-button><calcite-button .disabled=${this._saveDisabled || y(this._configContextConsumer.value)} kind=brand .loading=${this._solutionItemsTitlesUpdating} @click=${this._commitNameChanges}>${this._translations.applyChangesAndCloseTheDialog}</calcite-button></div>`;
  }
  _prefixInput() {
    clearTimeout(this._textInputTimeout), this._textInputTimeout = setTimeout(() => {
      this._prefixValue = this._prefixRef.value?.value || "", this._updateTemplates();
    }, 500);
  }
  _suffixInput() {
    clearTimeout(this._textInputTimeout), this._textInputTimeout = setTimeout(() => {
      this._suffixValue = this._suffixRef.value?.value || "", this._updateTemplates();
    }, 500);
  }
  _updateTemplates() {
    const e = this._configContextConsumer.value?.authentication?.CanUpdateSolution ?? !1, i = this._configContextConsumer.value?.authentication?.PortalUserName;
    this._templateInfos = this._templateInfos.map((t) => (this._loadingDefaultPrefix && t.title.startsWith(this._prefixValue) && (t.title = this._replaceStart(t.title, this._prefixValue, "")), this._loadingDefaultSuffix && t.title.endsWith(this._suffixValue) && (t.title = this._replaceAtEnd(t.title, this._suffixValue, "")), t));
    const a = JSON.parse(JSON.stringify(this._templateInfos));
    this._hasNameLengthError = !1, this._displayTemplateInfos = a.map((t) => {
      const s = this._prefixValue !== "", n = this._suffixValue !== "", d = this._defaultPrefix !== "", c = this._defaultSuffix !== "";
      if (t.owner !== i && !e)
        return t;
      let l = t.title;
      s && (d ? this._originalTitles.find((f) => f.id === t.id)?.title.startsWith(this._defaultPrefix) ? l = this._applyPrefixWithDuplicateCheck(t.title, this._prefixValue) : this._prefixValue !== this._defaultPrefix && (l = this._applyPrefixWithDuplicateCheck(t.title, this._prefixValue)) : l = this._applyPrefixWithDuplicateCheck(t.title, this._prefixValue));
      let o = l;
      return n && (c ? this._originalTitles.find((f) => f.id === t.id)?.title.endsWith(this._defaultSuffix) ? o = this._applySuffixWithDuplicateCheck(l, this._suffixValue) : this._suffixValue !== this._defaultSuffix && (o = this._applySuffixWithDuplicateCheck(l, this._suffixValue)) : o = this._applySuffixWithDuplicateCheck(l, this._suffixValue)), t.title = o, this._hasNameLengthError || (this._hasNameLengthError = t.title.length > b), t;
    }), this._loadingDefaultPrefix = !1, this._loadingDefaultSuffix = !1;
  }
  _replaceStart(e, i, a) {
    return e.startsWith(i) ? `${a}${e.slice(i.length)}` : e;
  }
  _replaceAtEnd(e, i, a) {
    return e.endsWith(i) ? `${e.substring(0, e.length - i.length)}${a}` : e;
  }
  _applyPrefixWithDuplicateCheck(e, i) {
    return !i || e.startsWith(i) ? e : i + e;
  }
  _applySuffixWithDuplicateCheck(e, i) {
    return !i || e.endsWith(i) ? e : e + i;
  }
  _hasChanges() {
    const e = this._defaultPrefix !== this._prefixValue, i = this._defaultSuffix !== this._suffixValue;
    return this._displayTemplateInfos.some((t) => {
      const s = this._originalTitles.find((n) => n.id === t.id);
      return s && s.title !== t.title;
    }) || e || i;
  }
  _closeDialog() {
    this.open = !1;
  }
  async _commitNameChanges() {
    if (!y(this._configContextConsumer.value)) {
      if (this._hasChanges()) {
        this._telemetry?.logEvent({
          category: V.DEPLOYMENTS,
          action: "Rename Items",
          dimensions: [
            this.card?.title || "",
            this.card?.deployCommonId || "",
            this.card?.deployVersion || "",
            this.source,
            O(this.card?.typeKeywords)
          ]
        }), this._solutionItemsTitlesUpdating = !0;
        const e = this._configContextConsumer.value?.authentication?.CanUpdateSolution ?? !1, i = this._configContextConsumer.value?.authentication?.PortalUserName, a = this._displayTemplateInfos.reduce((t, s) => {
          if (s.owner !== i) {
            if (e) {
              const n = {
                id: s.id,
                title: s.title
              };
              t.push(s.type === "Group" ? x(n, this._configContextConsumer.value.userSession) : g(n, this._configContextConsumer.value.userSession, void 0, { solutionOwner: this.card?.owner }));
            }
          } else {
            const n = {
              id: s.id,
              title: s.title
            };
            t.push(s.type === "Group" ? x(n, this._configContextConsumer.value.userSession) : g(n, this._configContextConsumer.value.userSession, void 0, { solutionOwner: this.card?.owner }));
          }
          return t;
        }, []);
        if (this.solutionData?.templates) {
          const t = {
            id: this.card.id
          }, s = {
            ...this.solutionData,
            titles: {
              prefix: this._prefixValue,
              suffix: this._suffixValue
            }
          };
          a.push(W(t, s, this._configContextConsumer.value.userSession, void 0, void 0, null, this.card?.owner));
        }
        await Promise.all(a), this._solutionItemsTitlesUpdating = !1, this.solutionItemsTitlesChanged.emit();
      }
      this._closeDialog();
    }
  }
}
v("solution-configure-titles", k);
export {
  k as SolutionConfigureTitles
};
