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 { UmbDictionaryImportRepository } from '../../repository/index.js';
import { css, html, customElement, query, state, when } from '../../../../external/lit/index.js';
import { UmbTextStyles } from '../../../core/style/index.js';
import { UmbModalBaseElement } from '../../../core/modal/index.js';
import { UmbId } from '../../../core/id/index.js';
import { TemporaryFileStatus, UmbTemporaryFileManager } from '../../../core/temporary-file/index.js';
let UmbImportDictionaryModalLayout = class UmbImportDictionaryModalLayout extends UmbModalBaseElement {
    #fileReader;
    #fileContent;
    #dictionaryImportRepository;
    #temporaryFileManager;
    #abortController;
    constructor() {
        super();
        this._selectionConfiguration = {
            multiple: false,
            selectable: true,
            selection: [],
        };
        this._parentUnique = null;
        this._temporaryFileId = '';
        this._importAllowed = false;
        this.#fileContent = [];
        this.#dictionaryImportRepository = new UmbDictionaryImportRepository(this);
        this.#temporaryFileManager = new UmbTemporaryFileManager(this);
        this.#fileReader = new FileReader();
        this.#fileReader.onload = (e) => {
            if (typeof e.target?.result === 'string') {
                const fileContent = e.target.result;
                this.#dictionaryPreviewBuilder(fileContent);
            }
        };
    }
    connectedCallback() {
        super.connectedCallback();
        this._parentUnique = this.data?.unique ?? null;
        this._selectionConfiguration.selection = this._parentUnique ? [this._parentUnique] : [];
    }
    async #submit() {
        const { error } = await this.#dictionaryImportRepository.requestImport(this._temporaryFileId, this._parentUnique);
        if (error)
            return;
        this._submitModal();
    }
    #dictionaryPreviewBuilder(htmlString) {
        const parser = new DOMParser();
        const doc = parser.parseFromString(htmlString, 'text/xml');
        const elements = doc.childNodes;
        this.#fileContent = this.#dictionaryPreviewItemBuilder(elements);
        this.requestUpdate();
    }
    #dictionaryPreviewItemBuilder(nodeList) {
        const items = [];
        const list = [];
        nodeList.forEach((node) => {
            if (node.nodeType === Node.ELEMENT_NODE && node.nodeName === 'DictionaryItem') {
                list.push(node);
            }
        });
        list.forEach((item) => {
            items.push({
                name: item.getAttribute('Name') ?? '',
                id: item.getAttribute('Key') ?? '',
                children: this.#dictionaryPreviewItemBuilder(item.childNodes) ?? undefined,
            });
        });
        return items;
    }
    async #onUpload(e) {
        e.preventDefault();
        this.#onClear();
        const formData = new FormData(this._form);
        const file = formData.get('file');
        if (!file)
            throw new Error('File is missing');
        this.#fileReader.readAsText(file);
        const temporaryUnique = UmbId.new();
        this.#abortController = new AbortController();
        const { status } = await this.#temporaryFileManager.uploadOne({
            file,
            temporaryUnique,
            abortController: this.#abortController,
        });
        if (status === TemporaryFileStatus.SUCCESS) {
            this._importAllowed = true;
            this._temporaryFileId = temporaryUnique;
        }
    }
    async #onFileInput() {
        requestAnimationFrame(() => {
            this._form.requestSubmit();
        });
    }
    #onClear() {
        this._temporaryFileId = '';
        this._importAllowed = false;
        this.#abortController?.abort();
        this.#abortController = undefined;
    }
    render() {
        return html ` <umb-body-layout headline=${this.localize.term('general_import')}>
			<uui-box>
				${when(this._temporaryFileId, () => this.#renderImportDestination(), () => this.#renderUploadZone())}
			</uui-box>
			<uui-button
				slot="actions"
				type="button"
				label=${this.localize.term('general_cancel')}
				@click=${this._rejectModal}></uui-button>
		</umb-body-layout>`;
    }
    #renderFileContents(items) {
        return html `${items.map((item) => {
            return html `${item.name}
				<div>${this.#renderFileContents(item.children)}</div>`;
        })}`;
    }
    #renderImportDestination() {
        return html `
			<div id="wrapper">
				<div>
					<strong><umb-localize key="visuallyHiddenTexts_dictionaryItems">Dictionary items</umb-localize>:</strong>
					<div id="item-list">${this.#renderFileContents(this.#fileContent)}</div>
				</div>

				${this.#renderNavigate()}
			</div>
		`;
    }
    #renderNavigate() {
        return html `<div id="nav">
			<uui-button label=${this.localize.term('general_import')} look="secondary" @click=${this.#onClear}>
				<uui-icon name="icon-arrow-left"></uui-icon>
				${this.localize.term('general_back')}
			</uui-button>
			<uui-button
				.state=${this._importButtonState}
				?disabled=${!this._importAllowed}
				type="button"
				label=${this.localize.term('general_import')}
				look="primary"
				@click=${this.#submit}></uui-button>
		</div>`;
    }
    #renderUploadZone() {
        return html `<umb-localize key="dictionary_importDictionaryItemHelp"></umb-localize>
			<uui-form>
				<form id="form" name="form" @submit=${this.#onUpload}>
					<uui-form-layout-item>
						<uui-label for="file" slot="label" required>${this.localize.term('dictionary_pickFile')}</uui-label>
						<uui-input-file
							accept=".udt"
							name="file"
							id="file"
							@input=${this.#onFileInput}
							required
							required-message=${this.localize.term('dictionary_pickFileRequired')}></uui-input-file>
					</uui-form-layout-item>
				</form>
			</uui-form>`;
    }
    static { this.styles = [
        UmbTextStyles,
        css `
			uui-input {
				width: 100%;
			}
			#item-list {
				padding: var(--uui-size-3) var(--uui-size-4);
				border: 1px solid var(--uui-color-border);
				border-radius: var(--uui-border-radius);
			}
			#item-list div {
				padding-left: 20px;
			}

			#wrapper {
				display: flex;
				flex-direction: column;
				gap: var(--uui-size-3);
			}
		`,
    ]; }
};
__decorate([
    state()
], UmbImportDictionaryModalLayout.prototype, "_selectionConfiguration", void 0);
__decorate([
    state()
], UmbImportDictionaryModalLayout.prototype, "_parentUnique", void 0);
__decorate([
    state()
], UmbImportDictionaryModalLayout.prototype, "_temporaryFileId", void 0);
__decorate([
    state()
], UmbImportDictionaryModalLayout.prototype, "_importButtonState", void 0);
__decorate([
    state()
], UmbImportDictionaryModalLayout.prototype, "_importAllowed", void 0);
__decorate([
    query('#form')
], UmbImportDictionaryModalLayout.prototype, "_form", void 0);
UmbImportDictionaryModalLayout = __decorate([
    customElement('umb-import-dictionary-modal')
], UmbImportDictionaryModalLayout);
export { UmbImportDictionaryModalLayout };
export default UmbImportDictionaryModalLayout;
