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_USER_WORKSPACE_CONTEXT } from '../../user-workspace.context-token.js';
import { css, html, customElement, query, nothing, state } from '../../../../../../../external/lit/index.js';
import { UmbLitElement } from '../../../../../../core/lit-element/index.js';
import { UmbTemporaryFileConfigRepository } from '../../../../../../core/temporary-file/index.js';
let UmbUserWorkspaceAvatarElement = class UmbUserWorkspaceAvatarElement extends UmbLitElement {
    #userWorkspaceContext;
    #temporaryFileConfigRepository;
    constructor() {
        super();
        this._allowedFileTypes = 'image/*';
        this.#temporaryFileConfigRepository = new UmbTemporaryFileConfigRepository(this);
        this.#observeUser = () => {
            this.observe(this.#userWorkspaceContext.data, async (user) => {
                this._user = user;
            }, 'umbUserObserver');
        };
        this.#uploadAvatar = async () => {
            try {
                const selectedFile = await this.#selectAvatar();
                this.#userWorkspaceContext?.uploadAvatar(selectedFile);
            }
            catch (error) {
                console.error(error);
            }
        };
        this.#deleteAvatar = async () => {
            if (!this.#userWorkspaceContext)
                return;
            await this.#userWorkspaceContext.deleteAvatar();
        };
        this.consumeContext(UMB_USER_WORKSPACE_CONTEXT, (instance) => {
            this.#userWorkspaceContext = instance;
            if (!this.#userWorkspaceContext)
                return;
            this.#observeUser();
        });
        this.#observeAllowedFileTypes();
    }
    getFormElement() {
        return this._selectElement;
    }
    async #observeAllowedFileTypes() {
        await this.#temporaryFileConfigRepository.initialized;
        this.observe(this.#temporaryFileConfigRepository.part('imageFileTypes'), (fileTypes) => {
            if (fileTypes.length) {
                this._allowedFileTypes = fileTypes.map((t) => `.${t}`).join(',');
            }
            else {
                this._allowedFileTypes = 'image/*';
            }
        }, '_imageFileTypes');
    }
    #observeUser;
    #uploadAvatar;
    #selectAvatar() {
        return new Promise((resolve, reject) => {
            if (!this._avatarFileField) {
                reject("Can't find avatar file field");
                return;
            }
            // Reset value to allow selecting the same file again
            this._avatarFileField.value = '';
            // Use { once: true } to auto-remove listener after first trigger
            this._avatarFileField.addEventListener('change', (event) => {
                const target = event?.target;
                const file = target.files?.[0];
                if (!file) {
                    reject("Can't find avatar file");
                    return;
                }
                resolve(file);
            }, { once: true });
            this._avatarFileField.click();
        });
    }
    #deleteAvatar;
    #hasAvatar() {
        if (!this._user)
            return false;
        return this._user.avatarUrls.length > 0;
    }
    render() {
        if (!this._user)
            return nothing;
        return html `
			<uui-box>
				<form id="AvatarUploadForm" novalidate>
					<umb-user-avatar
						id="Avatar"
						.name=${this._user.name}
						.kind=${this._user.kind}
						.imgUrls=${this._user.avatarUrls ?? []}></umb-user-avatar>
					<input id="AvatarFileField" type="file" name="avatarFile" accept=${this._allowedFileTypes} required hidden />
					<uui-button label="${this.localize.term('user_changePhoto')}" @click=${this.#uploadAvatar}></uui-button>
					${this.#hasAvatar()
            ? html `
								<uui-button
									type="button"
									label=${this.localize.term('user_removePhoto')}
									@click=${this.#deleteAvatar}></uui-button>
							`
            : nothing}
				</form>
			</uui-box>
		`;
    }
    static { this.styles = [
        css `
			:host {
				display: block;
			}

			#Avatar {
				font-size: 75px;
				place-self: center;
			}

			form {
				text-align: center;
				display: flex;
				flex-direction: column;
				gap: var(--uui-size-space-2);
			}
		`,
    ]; }
};
__decorate([
    state()
], UmbUserWorkspaceAvatarElement.prototype, "_user", void 0);
__decorate([
    state()
], UmbUserWorkspaceAvatarElement.prototype, "_allowedFileTypes", void 0);
__decorate([
    query('#AvatarFileField')
], UmbUserWorkspaceAvatarElement.prototype, "_avatarFileField", void 0);
__decorate([
    query('uui-combobox')
], UmbUserWorkspaceAvatarElement.prototype, "_selectElement", void 0);
UmbUserWorkspaceAvatarElement = __decorate([
    customElement('umb-user-workspace-avatar')
], UmbUserWorkspaceAvatarElement);
export { UmbUserWorkspaceAvatarElement };
export default UmbUserWorkspaceAvatarElement;
