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