var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { UmbDocumentVariantState } from '../../../types.js';
import { UMB_DOCUMENT_ITEM_REPOSITORY_ALIAS, UMB_DOCUMENT_REFERENCE_REPOSITORY_ALIAS } from '../../../constants.js';
import { UMB_DOCUMENT_CONFIGURATION_CONTEXT } from '../../../global-contexts/index.js';
import { css, customElement, html, nothing, state, when } from '../../../../../../external/lit/index.js';
import { UmbModalBaseElement } from '../../../../../core/modal/index.js';
import { UmbTextStyles } from '../../../../../core/style/index.js';
import { UmbSelectionManager } from '../../../../../core/utils/index.js';
import '../../../modals/shared/document-variant-language-picker.element.js';
/**
 * @function isPublished
 * @param {UmbDocumentVariantOptionModel} option - the option to check.
 * @returns {boolean} boolean
 */
export function isPublished(option) {
    return (option.variant?.state === UmbDocumentVariantState.PUBLISHED ||
        option.variant?.state === UmbDocumentVariantState.PUBLISHED_PENDING_CHANGES);
}
let UmbDocumentUnpublishModalElement = class UmbDocumentUnpublishModalElement extends UmbModalBaseElement {
    constructor() {
        super(...arguments);
        this._selectionManager = new UmbSelectionManager(this);
        this._options = [];
        this._selection = [];
        this._canUnpublish = true;
        this._hasInvalidSelection = true;
        this._isInvariant = false;
        this.#pickableFilter = (option) => {
            if (!option.variant) {
                return false;
            }
            return this.data?.pickableFilter ? this.data.pickableFilter(option) : true;
        };
        this._requiredFilter = (variantOption) => {
            return variantOption.language.isMandatory && !this._selection.includes(variantOption.unique);
        };
    }
    #pickableFilter;
    firstUpdated() {
        this.#configureReferences();
        // If invariant, don't display the variant selection component.
        if (this.data?.options.length === 1 && this.data.options[0].culture === null) {
            this._isInvariant = true;
            this._hasInvalidSelection = false;
            return;
        }
        this.#configureSelectionManager();
    }
    #configureReferences() {
        if (!this.data?.documentUnique)
            return;
        this._referencesConfig = {
            itemRepositoryAlias: UMB_DOCUMENT_ITEM_REPOSITORY_ALIAS,
            referenceRepositoryAlias: UMB_DOCUMENT_REFERENCE_REPOSITORY_ALIAS,
            unique: this.data.documentUnique,
        };
    }
    async #configureSelectionManager() {
        this._selectionManager.setMultiple(true);
        this._selectionManager.setSelectable(true);
        // Only display variants that are relevant to pick from, i.e. variants that are published or published with pending changes.
        // If we don't know the state (e.g. from a bulk publishing selection) we need to consider it available for selection.
        this._options =
            this.data?.options.filter((option) => (option.variant && option.variant.state === null) || isPublished(option)) ??
                [];
        let selected = this.value?.selection ?? [];
        const validOptions = this._options.filter((o) => this.#pickableFilter(o));
        // Filter selection based on options:
        selected = selected.filter((s) => validOptions.some((o) => o.unique === s));
        this._selectionManager.setSelection(selected);
        this.observe(this._selectionManager.selection, (selection) => {
            this._selection = selection;
            const selectionHasMandatory = this._options.some((o) => o.language.isMandatory && selection.includes(o.unique));
            const selectionDoesNotHaveAllMandatory = this._options.some((o) => o.language.isMandatory && !selection.includes(o.unique));
            this._hasInvalidSelection = selectionHasMandatory && selectionDoesNotHaveAllMandatory;
        }, 'observeSelection');
    }
    #submit() {
        if (this._canUnpublish) {
            const selection = this._isInvariant ? ['invariant'] : this._selection;
            this.value = { selection };
            this.modalContext?.submit();
            return;
        }
        this.modalContext?.reject();
    }
    #close() {
        this.modalContext?.reject();
    }
    async #onReferencesChange(event) {
        event.stopPropagation();
        const target = event.target;
        const getReferencedByTotal = target.getTotalReferencedBy();
        const descendantsWithReferencesTotal = target.getTotalDescendantsWithReferences();
        const total = getReferencedByTotal + descendantsWithReferencesTotal;
        if (total > 0) {
            const context = await this.getContext(UMB_DOCUMENT_CONFIGURATION_CONTEXT);
            this._canUnpublish = (await context?.getDocumentConfiguration())?.disableUnpublishWhenReferenced === false;
        }
    }
    render() {
        return html `<uui-dialog-layout headline=${this.localize.term('content_unpublish')}>
			<p>
				<umb-localize key="prompt_confirmUnpublish"></umb-localize>
			</p>
			${when(!this._isInvariant, () => html `
					<umb-document-variant-language-picker
						.selectionManager=${this._selectionManager}
						.variantLanguageOptions=${this._options}
						.requiredFilter=${this._hasInvalidSelection ? this._requiredFilter : undefined}
						.pickableFilter=${this.#pickableFilter}></umb-document-variant-language-picker>
				`)}
			${this._referencesConfig
            ? html `<umb-confirm-action-modal-entity-references
						.config=${this._referencesConfig}
						@change=${this.#onReferencesChange}></umb-confirm-action-modal-entity-references>`
            : nothing}

			<div slot="actions">
				<uui-button label=${this.localize.term('general_close')} @click=${this.#close}></uui-button>
				<uui-button
					label="${this.localize.term('actions_unpublish')}"
					?disabled=${this._hasInvalidSelection ||
            !this._canUnpublish ||
            (!this._isInvariant && this._selection.length === 0)}
					look="primary"
					color="warning"
					@click=${this.#submit}></uui-button>
			</div>
		</uui-dialog-layout> `;
    }
    static { this.styles = [
        UmbTextStyles,
        css `
			:host {
				display: block;
				min-width: 600px;
				max-width: 90vw;
			}

			#references {
				--uui-table-cell-padding: 0;
			}

			#references-warning {
				margin-top: 1rem;
				background-color: var(--uui-color-danger);
				color: var(--uui-color-danger-contrast);
			}
		`,
    ]; }
};
__decorate([
    state()
], UmbDocumentUnpublishModalElement.prototype, "_options", void 0);
__decorate([
    state()
], UmbDocumentUnpublishModalElement.prototype, "_selection", void 0);
__decorate([
    state()
], UmbDocumentUnpublishModalElement.prototype, "_canUnpublish", void 0);
__decorate([
    state()
], UmbDocumentUnpublishModalElement.prototype, "_hasInvalidSelection", void 0);
__decorate([
    state()
], UmbDocumentUnpublishModalElement.prototype, "_isInvariant", void 0);
__decorate([
    state()
], UmbDocumentUnpublishModalElement.prototype, "_referencesConfig", void 0);
UmbDocumentUnpublishModalElement = __decorate([
    customElement('umb-document-unpublish-modal')
], UmbDocumentUnpublishModalElement);
export { UmbDocumentUnpublishModalElement };
export default UmbDocumentUnpublishModalElement;
