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 { UMB_CURRENT_USER_MFA_ENABLE_PROVIDER_MODAL } from '../current-user-mfa-enable/current-user-mfa-enable-modal.token.js';
import { UmbCurrentUserRepository } from '../../repository/index.js';
import { UMB_CURRENT_USER_MFA_DISABLE_PROVIDER_MODAL } from '../current-user-mfa-disable/current-user-mfa-disable-modal.token.js';
import { css, customElement, html, nothing, property, repeat, state, when } from '../../../../../external/lit/index.js';
import { UmbLitElement } from '../../../../core/lit-element/index.js';
import { umbOpenModal } from '../../../../core/modal/index.js';
import { UmbTextStyles } from '../../../../core/style/index.js';
import { umbExtensionsRegistry } from '../../../../core/extension-registry/index.js';
import { mergeObservables } from '../../../../../libs/observable-api/index.js';
let UmbCurrentUserMfaModalElement = class UmbCurrentUserMfaModalElement extends UmbLitElement {
    #currentUserRepository;
    constructor() {
        super();
        this._items = [];
        this._isLoading = true;
        this.#currentUserRepository = new UmbCurrentUserRepository(this);
        this.#loadProviders();
    }
    async #loadProviders() {
        this._isLoading = true;
        this._error = undefined;
        try {
            const serverLoginProvidersResponse = await this.#currentUserRepository.requestMfaLoginProviders();
            if (serverLoginProvidersResponse.error) {
                this._error = this.localize.term('errors_defaultError');
                this._isLoading = false;
                return;
            }
            const serverLoginProviders$ = serverLoginProvidersResponse.asObservable();
            const manifestLoginProviders$ = umbExtensionsRegistry.byType('mfaLoginProvider');
            // Merge the server and manifest providers to get the final list of providers
            const mfaLoginProviders$ = mergeObservables([serverLoginProviders$, manifestLoginProviders$], ([serverLoginProviders, manifestLoginProviders]) => {
                return manifestLoginProviders.map((manifestLoginProvider) => {
                    const serverLoginProvider = serverLoginProviders.find((serverLoginProvider) => serverLoginProvider.providerName === manifestLoginProvider.forProviderName);
                    return {
                        existsOnServer: !!serverLoginProvider,
                        isEnabledOnUser: serverLoginProvider?.isEnabledOnUser ?? false,
                        providerName: serverLoginProvider?.providerName ?? manifestLoginProvider.forProviderName,
                        displayName: manifestLoginProvider.meta?.label ?? serverLoginProvider?.providerName ?? manifestLoginProvider.name,
                    };
                });
            });
            this.observe(mfaLoginProviders$, (providers) => {
                this._items = providers;
                this._isLoading = false;
            }, '_mfaLoginProviders');
        }
        catch {
            this._error = this.localize.term('errors_defaultError');
            this._isLoading = false;
        }
    }
    #close() {
        this.modalContext?.submit();
    }
    #renderContent() {
        if (this._isLoading) {
            return html `<div id="loader"><uui-loader></uui-loader></div>`;
        }
        if (this._error) {
            return html `<p>${this._error}</p>`;
        }
        if (this._items.length > 0) {
            return html `
				${repeat(this._items, (item) => item.providerName, (item) => this.#renderProvider(item))}
			`;
        }
        return nothing;
    }
    render() {
        return html `
			<umb-body-layout headline="${this.localize.term('member_2fa')}">
				<div id="main">${this.#renderContent()}</div>
				<div slot="actions">
					<uui-button @click=${this.#close} look="secondary" .label=${this.localize.term('general_close')}></uui-button>
				</div>
			</umb-body-layout>
		`;
    }
    /**
     * Render a provider with a toggle to enable/disable it
     * @param item
     */
    #renderProvider(item) {
        return html `
			<uui-box headline=${item.displayName}>
				${when(item.existsOnServer, () => nothing, () => html `<div style="position:relative" slot="header-actions">
							<uui-badge
								style="cursor:default"
								title="Warning: This provider is not configured on the server"
								color="danger"
								look="primary">
								!
							</uui-badge>
						</div>`)}
				${when(item.isEnabledOnUser, () => html `
						<p style="margin-top:0">
							<umb-localize key="user_2faProviderIsEnabled">This two-factor provider is enabled</umb-localize>
						</p>
						<uui-button
							type="button"
							look="secondary"
							color="danger"
							.label=${this.localize.term('actions_disable')}
							@click=${() => this.#onProviderDisable(item)}></uui-button>
					`, () => html `
						<uui-button
							type="button"
							look="secondary"
							?disabled=${!item.existsOnServer}
							.label=${this.localize.term('actions_enable')}
							@click=${() => this.#onProviderEnable(item)}></uui-button>
					`)}
			</uui-box>
		`;
    }
    /**
     * Open the provider modal.
     * This will show the QR code and/or other means of validation for the given provider and return the activation code.
     * The activation code is then used to either enable the provider.
     * @param item
     */
    async #onProviderEnable(item) {
        await umbOpenModal(this, UMB_CURRENT_USER_MFA_ENABLE_PROVIDER_MODAL, {
            data: { providerName: item.providerName, displayName: item.displayName },
        }).catch(() => undefined);
    }
    /**
     * Open the provider modal.
     * This will show the QR code and/or other means of validation for the given provider and return the activation code.
     * The activation code is then used to disable the provider.
     * @param item
     */
    async #onProviderDisable(item) {
        await umbOpenModal(this, UMB_CURRENT_USER_MFA_DISABLE_PROVIDER_MODAL, {
            data: { providerName: item.providerName, displayName: item.displayName },
        }).catch(() => undefined);
    }
    static { this.styles = [
        UmbTextStyles,
        css `
			uui-box {
				margin-bottom: var(--uui-size-space-3);
			}

			#loader {
				display: flex;
				justify-content: center;
				align-items: center;
			}
		`,
    ]; }
};
__decorate([
    property({ attribute: false })
], UmbCurrentUserMfaModalElement.prototype, "modalContext", void 0);
__decorate([
    state()
], UmbCurrentUserMfaModalElement.prototype, "_items", void 0);
__decorate([
    state()
], UmbCurrentUserMfaModalElement.prototype, "_isLoading", void 0);
__decorate([
    state()
], UmbCurrentUserMfaModalElement.prototype, "_error", void 0);
UmbCurrentUserMfaModalElement = __decorate([
    customElement('umb-current-user-mfa-modal')
], UmbCurrentUserMfaModalElement);
export { UmbCurrentUserMfaModalElement };
export default UmbCurrentUserMfaModalElement;
