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_MEDIA_ENTITY_TYPE } from '../../entity.js';
import { css, customElement, html, ifDefined, property, state } from '../../../../../external/lit/index.js';
import { assignToFrozenObject } from '../../../../../libs/observable-api/index.js';
import { UmbChangeEvent } from '../../../../core/event/index.js';
import { UmbFileDropzoneItemStatus } from '../../../dropzone/index.js';
import { UmbLitElement } from '../../../../core/lit-element/index.js';
import { UMB_NAMEABLE_PROPERTY_DATASET_CONTEXT } from '../../../../core/property/index.js';
import { UmbTextStyles } from '../../../../core/style/index.js';
import { UmbTemporaryFileConfigRepository } from '../../../../core/temporary-file/index.js';
import { UMB_VALIDATION_EMPTY_LOCALIZATION_KEY, UmbFormControlMixin } from '../../../../core/validation/index.js';
import './image-cropper-field.element.js';
import './image-cropper-focus-setter.element.js';
import './image-cropper-preview.element.js';
import './image-cropper.element.js';
const DefaultFocalPoint = { left: 0.5, top: 0.5 };
const DefaultValue = {
    temporaryFileId: null,
    src: '',
    crops: [],
    focalPoint: DefaultFocalPoint,
};
let UmbInputImageCropperElement = class UmbInputImageCropperElement extends UmbFormControlMixin(UmbLitElement, undefined) {
    #config;
    constructor() {
        super();
        this.crops = [];
        this._loading = true;
        this.#config = new UmbTemporaryFileConfigRepository(this);
        this.#onRemove = () => {
            this.value = undefined;
            this._file?.temporaryFile?.abortController?.abort();
            this._file = undefined;
            this.dispatchEvent(new UmbChangeEvent());
        };
        this.addValidator('valueMissing', () => this.requiredMessage ?? UMB_VALIDATION_EMPTY_LOCALIZATION_KEY, () => {
            return !!this.required && (!this.value || (this.value.src === '' && this.value.temporaryFileId == null));
        });
    }
    firstUpdated() {
        this.#mergeCrops();
        this.#observeAcceptedFileTypes();
    }
    async #observeAcceptedFileTypes() {
        await this.#config.initialized;
        this.observe(this.#config.part('imageFileTypes'), (imageFileTypes) => {
            this._accept = imageFileTypes.join(',');
            this._loading = false;
        }, '_observeFileTypes');
    }
    #onUpload(e) {
        e.stopImmediatePropagation();
        const target = e.target;
        const file = target.value?.[0];
        if (file?.status !== UmbFileDropzoneItemStatus.COMPLETE)
            return;
        this._file = file;
        const underlyingFile = file.temporaryFile?.file;
        if (underlyingFile) {
            void this.#ensureMediaNameFromFile(underlyingFile);
        }
        this.value = assignToFrozenObject(this.value ?? DefaultValue, {
            temporaryFileId: file.temporaryFile?.temporaryUnique,
        });
        this.dispatchEvent(new UmbChangeEvent());
    }
    async #ensureMediaNameFromFile(file) {
        const datasetContext = await this.getContext(UMB_NAMEABLE_PROPERTY_DATASET_CONTEXT);
        if (!datasetContext || datasetContext.getEntityType() !== UMB_MEDIA_ENTITY_TYPE)
            return;
        const currentName = datasetContext.getName();
        if (currentName && currentName.trim() !== '')
            return;
        datasetContext.setName(file.name);
    }
    #onRemove;
    #mergeCrops() {
        if (this.value) {
            // Replace crops from the value with the crops from the config while keeping the coordinates from the value if they exist.
            const filteredCrops = this.crops.map((crop) => {
                const cropFromValue = this.value.crops.find((valueCrop) => valueCrop.alias === crop.alias);
                const result = {
                    ...crop,
                    coordinates: cropFromValue?.coordinates ?? undefined,
                };
                return result;
            });
            this.value = {
                ...this.value,
                crops: filteredCrops,
            };
        }
    }
    render() {
        if (this._loading) {
            return html `<div id="loader"><uui-loader></uui-loader></div>`;
        }
        if (this.value?.src || this._file) {
            return this.#renderImageCropper();
        }
        return this.#renderDropzone();
    }
    #renderDropzone() {
        return html `
			<umb-input-dropzone
				standalone
				accept=${ifDefined(this._accept)}
				disable-folder-upload
				@change="${this.#onUpload}"></umb-input-dropzone>
		`;
    }
    #onChange(e) {
        const value = e.target.value;
        if (!value) {
            this.value = undefined;
            this.dispatchEvent(new UmbChangeEvent());
            return;
        }
        if (this.value && this.value.temporaryFileId) {
            value.temporaryFileId = this.value.temporaryFileId;
        }
        if (value.temporaryFileId || value.src !== '') {
            this.value = value;
        }
        this.dispatchEvent(new UmbChangeEvent());
    }
    #renderImageCropper() {
        return html `
			<umb-image-cropper-field .value=${this.value} .file=${this._file?.temporaryFile?.file} @change=${this.#onChange}>
				<uui-button slot="actions" compact label=${this.localize.term('content_uploadClear')} @click=${this.#onRemove}>
					<uui-icon name="icon-trash"></uui-icon>
					<umb-localize key="content_uploadClear">Clear file(s)</umb-localize>
				</uui-button>
			</umb-image-cropper-field>
		`;
    }
    static { this.styles = [
        UmbTextStyles,
        css `
			umb-input-dropzone {
				max-width: 500px;
				min-width: 300px;
			}

			#loader {
				display: flex;
				justify-content: center;
			}

			[slot='actions'] {
				uui-icon {
					padding-right: var(--uui-size-1);
				}
			}
		`,
    ]; }
};
__decorate([
    property({ type: Boolean })
], UmbInputImageCropperElement.prototype, "required", void 0);
__decorate([
    property({ type: String })
], UmbInputImageCropperElement.prototype, "requiredMessage", void 0);
__decorate([
    property({ attribute: false })
], UmbInputImageCropperElement.prototype, "crops", void 0);
__decorate([
    state()
], UmbInputImageCropperElement.prototype, "_file", void 0);
__decorate([
    state()
], UmbInputImageCropperElement.prototype, "_accept", void 0);
__decorate([
    state()
], UmbInputImageCropperElement.prototype, "_loading", void 0);
UmbInputImageCropperElement = __decorate([
    customElement('umb-input-image-cropper')
], UmbInputImageCropperElement);
export { UmbInputImageCropperElement };
