/* COPYRIGHT Esri - https://js.arcgis.com/1.2/LICENSE.txt */
import { c as customElement } from "../../chunks/runtime.js";
import { css, nothing, html } from "lit";
import { u as useT9n } from "../../chunks/useT9n.js";
import { LitElement, createEvent, safeClassMap } from "@arcgis/lumina";
import { useContextConsumer } from "@arcgis/lumina/context";
import { g as getItemUrl } from "../../chunks/common.js";
import { T as TELEMETRY_CATEGORY } from "../../chunks/interfaces.js";
import { deleteSolution } from "@esri/solution-common";
import { c as configContext } from "../../chunks/deployAppContexts.js";
import { createRef, ref } from "lit-html/directives/ref.js";
import "../solution-item-accordion/customElement.js";
import { p as processTemplates, g as getRelatedSolutionsInfos } from "../../chunks/getRelatedInfos.js";
const styles = css`/** @license
 * Copyright 2025 Esri
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

.panel-bg-color {
  --calcite-panel-header-background-color: var(--calcite-color-foreground-1);
  --calcite-panel-background-color: var(--calcite-color-foreground-1);
}

.display-none {
  display: none;
}`;
class SolutionDeleteDialog extends LitElement {
  constructor() {
    super();
    this.open = false;
    this.source = "Card Dropdown";
    this._deletePercentage = 0;
    this._fetchingTemplates = false;
    this._isDeleteInProgress = false;
    this._nonSolutionDependencyItems = [];
    this._showDeleteError = false;
    this._showUndeletableItems = false;
    this._templateInfos = [];
    this._translations = useT9n({ name: "solution-delete-dialog", blocking: true });
    this._accordion = createRef();
    this._configContextConsumer = useContextConsumer({
      context: configContext,
      subscribe: true
    });
    this.solutionDeleteDialogOpen = createEvent();
    this.solutionDeleted = createEvent();
    this.solutionDeleteDialogBeforeClose = createEvent();
    this.listenOn(window, "beforeunload", (evt) => {
      if (this._isDeleteInProgress) {
        evt.preventDefault();
        evt.returnValue = true;
      }
    });
  }
  static {
    this.properties = { card: [0, {}, { attribute: false }], open: [5, {}, { type: Boolean }], source: 1, _deletePercentage: [16, {}, { state: true }], _fetchingTemplates: [16, {}, { state: true }], _isDeleteInProgress: [16, {}, { state: true }], _nonSolutionDependencyItems: [16, {}, { state: true }], _showDeleteError: [16, {}, { state: true }], _showUndeletableItems: [16, {}, { state: true }], _templateInfos: [16, {}, { state: true }], _translations: [16, {}, { state: true }] };
  }
  static {
    this.styles = styles;
  }
  get _telemetry() {
    return this._configContextConsumer.value?.telemetrySession;
  }
  close() {
    if (this._showUndeletableItems) {
      this.solutionDeleted.emit({ showAlert: false, refreshSolutionsTimeout: true, solutionTitle: this.card?.title });
    }
    this._showDeleteError = false;
    this._showUndeletableItems = false;
    this._isDeleteInProgress = false;
    this.open = false;
    this.solutionDeleteDialogOpen.emit(false);
  }
  delete() {
    this._telemetry?.logEvent({
      category: TELEMETRY_CATEGORY.DEPLOYMENTS,
      action: "Delete Solution",
      dimensions: [
        this.card?.title || "",
        this.card?.deployCommonId || "",
        this.card?.deployVersion || "",
        this.source
      ]
    });
    this._isDeleteInProgress = true;
    if (this.card) {
      const fallbackItemList = [{
        "itemName": this.card.title,
        "itemType": "Solution",
        "owner": this.card.owner,
        "modified": this.card.modified
      }];
      const options = {
        progressCallback: (percentDone) => {
          this._deletePercentage = Math.round(percentDone);
        }
      };
      void deleteSolution(this.card.id, this._configContextConsumer.value.userSession, options).then((deletes) => {
        const failedSummary = deletes[1];
        let failedDeletes;
        if (failedSummary) {
          failedDeletes = failedSummary.items.map((template) => {
            const partialItem = {
              "itemName": template.title,
              "itemType": template.type,
              "owner": template.owner,
              "modified": template.modified
            };
            return partialItem;
          });
        } else {
          failedDeletes = fallbackItemList;
        }
        if (failedDeletes.length === 0) {
          this.solutionDeleted.emit({ showAlert: true, refreshSolutionsTimeout: true, solutionTitle: this.card?.title });
          this._isDeleteInProgress = false;
          this.open = false;
        } else {
          const hasSolutionItem = failedDeletes.some((item) => item.itemType === "Solution");
          if (hasSolutionItem) {
            if (this.card) {
              void processTemplates(this.card, this._configContextConsumer.value.userSession).then((templates) => {
                this._templateInfos = templates;
                this._showDeleteError = true;
                this._showUndeletableItems = true;
                this._isDeleteInProgress = false;
              });
            } else {
              this._showDeleteError = true;
              this._isDeleteInProgress = false;
            }
          } else {
            if (this.card) {
              let resultFailedDeletes = [];
              resultFailedDeletes = failedSummary.items.map((template) => {
                const partialItem = {
                  "id": template.id,
                  "title": template.title,
                  "type": template.type,
                  "owner": template.owner,
                  "modified": template.modified,
                  "typeKeywords": [],
                  "snippet": "",
                  "dependencies": [],
                  "url": getItemUrl(template.id, this._configContextConsumer.value.authentication)
                };
                return partialItem;
              });
              this._templateInfos = resultFailedDeletes;
              this._showDeleteError = false;
              this._showUndeletableItems = true;
              this._isDeleteInProgress = false;
            } else {
              this.solutionDeleted.emit({ showAlert: true, refreshSolutionsTimeout: true });
              this._isDeleteInProgress = false;
              this.open = false;
            }
          }
        }
      });
    }
  }
  willUpdate(_changedProperties) {
    if (_changedProperties.has("open")) {
      const oldValue = _changedProperties.get("open");
      if (this.open && !oldValue) {
        this._fetchingTemplates = true;
        void getRelatedSolutionsInfos(this._configContextConsumer.value.userSession, this.card).then((relatedInfos) => {
          this._templateInfos = relatedInfos.templateInfos;
          this._nonSolutionDependencyItems = relatedInfos._nonSolutionDependencyItems;
          setTimeout(() => {
            this._accordion.value.expandFirstItem();
            if (relatedInfos.uniqueIitemIds.length > 0) {
              this._accordion.value.expandItems(relatedInfos.uniqueIitemIds);
            }
          }, 500);
          this._fetchingTemplates = false;
        });
      }
    }
  }
  updated(_changedProperties) {
    if (_changedProperties.has("_showUndeletableItems")) {
      if (this._showUndeletableItems !== _changedProperties.get("_showUndeletableItems")) {
        this._accordion.value.expandItems(this._templateInfos.map((template) => template.id));
      }
    }
  }
  render() {
    const loaderClass = this._fetchingTemplates ? "" : "display-none";
    const displayClass = this._fetchingTemplates ? "display-none" : "";
    const justDependencies = [...new Set(this._nonSolutionDependencyItems.map((dep) => dep.controlItemId))];
    const deleteableCount = this._templateInfos.length - this._getDependencyCount();
    const deleteableCountText = this._translations.deletionCount.replace("{{deleteableCount}}", deleteableCount.toString()).replace("{{totalCount}}", this._templateInfos.length.toString());
    return html`<calcite-dialog class="panel-bg-color" .closeDisabled=${this._isDeleteInProgress} .heading=${this._translations.title.replace("{{solution}}", this.card?.title ?? "")} id=${this._translations.title.replace("{{solution}}", this.card?.title ?? "") ?? nothing} modal kind=danger .open=${this.open} width=l outside-close-disabled @calciteDialogBeforeClose=${() => {
      this.solutionDeleteDialogBeforeClose.emit();
    }} @calciteDialogClose=${() => {
      this.open = false;
      this.solutionDeleteDialogOpen.emit(false);
    }}>${this._isDeleteInProgress ? html`<calcite-loader .label=${this._translations.deleteInProgress} scale=l .text=${this._translations.deleteInProgress} type=determinate-value .value=${this._deletePercentage}></calcite-loader>` : this._showUndeletableItems ? html`<calcite-label class=${safeClassMap(displayClass)} layout=inline>${this._translations.failedToDeleteItems}</calcite-label><solution-item-accordion class=${safeClassMap(displayClass)} .itemRelationshipDependencies=${[]} link-type=item list-selection-mode=multiple .reuseWarning=${this._translations.itemDependencyReusewarning} .templateInfos=${this._templateInfos} .typeKeywords=${this.card?.typeKeywords} ${ref(this._accordion)}></solution-item-accordion><calcite-button appearance=outline @click=${this.close} slot=footer-end>${this._translations.buttonClose}</calcite-button>` : html`<calcite-label class=${safeClassMap(displayClass)} layout=inline scale=l>${this._translations.deletionNote}<calcite-chip .label=${deleteableCountText} scale=m icon=information>${deleteableCountText}</calcite-chip></calcite-label><calcite-loader class=${safeClassMap(loaderClass)} label></calcite-loader><solution-item-accordion class=${safeClassMap(displayClass)} .itemRelationshipDependencies=${justDependencies} link-type=item list-selection-mode=multiple .reuseWarning=${this._translations.itemDependencyReusewarning} .templateInfos=${this._templateInfos} .typeKeywords=${this.card?.typeKeywords} ${ref(this._accordion)}></solution-item-accordion><calcite-button appearance=outline @click=${this.close} slot=footer-end>${this._translations.buttonCancel}</calcite-button><calcite-button @click=${() => {
      this.delete();
    }} slot=footer-end kind=danger>${this._translations.buttonDelete}</calcite-button>${this._showDeleteError && html`<calcite-alert icon=exclamation-mark-triangle kind=danger .label=${this._translations.failedToDelete} @calciteAlertClose=${() => {
      this._showDeleteError = false;
    }} open><div slot=message>${this._translations.failedToDelete}</div></calcite-alert>` || ""}`}</calcite-dialog>`;
  }
  _getDependencyCount() {
    const controlItemsArray = this._nonSolutionDependencyItems.map((dep) => dep.controlItemId);
    const uniqueControlItems = [...new Set(controlItemsArray)];
    return uniqueControlItems.length;
  }
}
customElement("solution-delete-dialog", SolutionDeleteDialog);
export {
  SolutionDeleteDialog
};
