/* COPYRIGHT Esri - https://js.arcgis.com/5.0/LICENSE.txt */
import { c as C } from "../../chunks/runtime.js";
import { u as y } from "../../chunks/useT9n.js";
import { LitElement as S, createEvent as c, safeClassMap as f } from "@arcgis/lumina";
import { useContextConsumer as T } from "@arcgis/lumina/context";
import { css as D, html as u } from "lit";
import { A as v, C as m, I as $, T as P } from "../../chunks/interfaces.js";
import { createRef as _, ref as p } from "lit-html/directives/ref.js";
import * as b from "@esri/solution-common";
import { updateGroup as V, updateItem as E, updateItemExtended as w } from "@esri/solution-common";
import { g as W } from "../../chunks/getRelatedInfos.js";
const L = D`*[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 S {
  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 = y({ name: "solution-configure-titles", blocking: !0 }), this._configContextConsumer = T({
      context: v,
      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 = c(), this.solutionItemsTitlesChanged = c();
  }
  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 = L;
  }
  async willUpdate(i) {
    if (i.has("templateInfos") && (this._templateInfos = JSON.parse(JSON.stringify(this.templateInfos)), this._updateTemplates()), i.has("open")) {
      const t = i.get("open");
      if (this.open && !t) {
        await this._updatePrefixSuffix(), this._templateInfos = JSON.parse(JSON.stringify(this.templateInfos)), this._originalTitles = this._templateInfos.map((s) => ({ id: s.id, title: s.title })), this._updateTemplates();
        const e = await W(this._configContextConsumer.value.userSession, this.card);
        this._nonSolutionDependencyItems = e._nonSolutionDependencyItems, await this._accordionRef?.expandFirstItem();
      }
    }
  }
  get _telemetry() {
    return this._configContextConsumer.value?.telemetrySession;
  }
  async load() {
    this._updateTemplates(), await this._updatePrefixSuffix();
  }
  async _updatePrefixSuffix() {
    this.solutionData = await b.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 u`<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 i = m(this._prefixValue, "item"), t = this._hasNameLengthError && this._prefixValue.length > 0, e = !i, s = !t, n = e ? "display-none" : "", r = s ? "display-none" : "", a = e && s ? "valid" : "invalid", o = m(this._suffixValue, "item"), h = this._hasNameLengthError && this._suffixValue.length > 0, l = !o, d = !h, x = l ? "display-none" : "", g = d ? "display-none" : "", I = l && d ? "valid" : "invalid";
    return this._saveDisabled = !e || !s || !l || !d || !this._hasChanges(), u`<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=${a} .value=${this._prefixValue} ${p(this._prefixRef)}></calcite-input><calcite-input-message class=${f(n)} icon=exclamation-mark-triangle status=invalid>${this._translations.invalidPrefixOrSuffixCharsError}</calcite-input-message><calcite-input-message class=${f(r)} 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=${I} .value=${this._suffixValue} ${p(this._suffixRef)}></calcite-input><calcite-input-message class=${f(x)} icon=exclamation-mark-triangle status=invalid>${this._translations.invalidPrefixOrSuffixCharsError}</calcite-input-message><calcite-input-message class=${f(g)} icon=exclamation-mark-triangle status=invalid>${this._translations.invalidPrefixOrSuffixLengthError}</calcite-input-message></calcite-label></div></div>`;
  }
  _getAccordion() {
    const i = [...new Set(this._nonSolutionDependencyItems.map((t) => t.controlItemId))];
    return u`<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=${i} list-selection-mode=multiple .reuseWarning=${this._translations.itemDependencyReuseWarning} .templateInfos=${this._displayTemplateInfos} .typeKeywords=${this.card?.typeKeywords} ${p(async (t) => {
      t && (this._accordionRef = t);
    })}></solution-item-accordion></div>`;
  }
  _getDialogButtons() {
    return u`<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} 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() {
    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 i = JSON.parse(JSON.stringify(this._templateInfos));
    this._hasNameLengthError = !1, this._displayTemplateInfos = i.map((t) => {
      const e = this._prefixValue !== "", s = this._suffixValue !== "", n = this._defaultPrefix !== "", r = this._defaultSuffix !== "";
      let a = t.title;
      e && (n ? this._originalTitles.find((l) => l.id === t.id)?.title.startsWith(this._defaultPrefix) ? a = this._applyPrefixWithDuplicateCheck(t.title, this._prefixValue) : this._prefixValue !== this._defaultPrefix && (a = this._applyPrefixWithDuplicateCheck(t.title, this._prefixValue)) : a = this._applyPrefixWithDuplicateCheck(t.title, this._prefixValue));
      let o = a;
      return s && (r ? this._originalTitles.find((l) => l.id === t.id)?.title.endsWith(this._defaultSuffix) ? o = this._applySuffixWithDuplicateCheck(a, this._suffixValue) : this._suffixValue !== this._defaultSuffix && (o = this._applySuffixWithDuplicateCheck(a, this._suffixValue)) : o = this._applySuffixWithDuplicateCheck(a, this._suffixValue)), t.title = o, this._hasNameLengthError || (this._hasNameLengthError = t.title.length > $), t;
    }), this._loadingDefaultPrefix = !1, this._loadingDefaultSuffix = !1;
  }
  _replaceStart(i, t, e) {
    return i.startsWith(t) ? `${e}${i.slice(t.length)}` : i;
  }
  _replaceAtEnd(i, t, e) {
    return i.endsWith(t) ? `${i.substring(0, i.length - t.length)}${e}` : i;
  }
  _applyPrefixWithDuplicateCheck(i, t) {
    return !t || i.startsWith(t) ? i : t + i;
  }
  _applySuffixWithDuplicateCheck(i, t) {
    return !t || i.endsWith(t) ? i : i + t;
  }
  _hasChanges() {
    const i = this._defaultPrefix !== this._prefixValue, t = this._defaultSuffix !== this._suffixValue;
    return this._displayTemplateInfos.some((s) => {
      const n = this._originalTitles.find((r) => r.id === s.id);
      return n && n.title !== s.title;
    }) || i || t;
  }
  _closeDialog() {
    this.open = !1;
  }
  async _commitNameChanges() {
    if (this._hasChanges()) {
      this._telemetry?.logEvent({
        category: P.DEPLOYMENTS,
        action: "Rename Items",
        dimensions: [
          this.card?.title || "",
          this.card?.deployCommonId || "",
          this.card?.deployVersion || "",
          this.source
        ]
      }), this._solutionItemsTitlesUpdating = !0;
      const i = this._displayTemplateInfos.reduce((t, e) => {
        const s = {
          id: e.id,
          title: e.title
        };
        return t.push(e.type === "Group" ? V(s, this._configContextConsumer.value.userSession) : E(s, this._configContextConsumer.value.userSession, void 0, { solutionOwner: this.card?.owner })), t;
      }, []);
      if (this.solutionData?.templates) {
        const t = {
          id: this.card.id
        }, e = {
          ...this.solutionData,
          titles: {
            prefix: this._prefixValue,
            suffix: this._suffixValue
          }
        };
        i.push(w(t, e, this._configContextConsumer.value.userSession, void 0, void 0, null, this.card?.owner));
      }
      await Promise.all(i), this._solutionItemsTitlesUpdating = !1, this.solutionItemsTitlesChanged.emit();
    }
    this._closeDialog();
  }
}
C("solution-configure-titles", k);
export {
  k as SolutionConfigureTitles
};
