/* eslint-disable @typescript-eslint/no-explicit-any */
import { Fragment, h } from "@stencil/core";
import { _t } from "../../../text";
import { randomIdGenerator } from "../../../global/utils/randomIdGenerator";
import { FormFileUploadVariation } from "./form-file-upload-variation.enum";
import { FormFileUploadValidation } from "./form-file-upload-validation.enum";
import { FormFileUploadHeadingLevel } from "./form-file-upload-heading-level.enum";
import { UtilBreakpointObserverBreakpoints } from "../../_util/util-breakpoint-observer/util-breakpoint-observer-breakpoints.enum";
import { FormValidationMessageVariation } from "../form-validation-message/form-validation-message-variation.enum";
/**
 *	@enums FormInputFileType - form-input-file-type.enum.ts
 *  @enums FormInputFileVariation - form-input-file-variation.enum.ts
 * 	@swedishName Filuppladdare
 */
export class FormFileUpload {
    constructor() {
        this.toBase64 = (file) => new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () => {
                const encoded = reader.result.toString().replace(/^data:(.*,)?/, '');
                resolve(encoded);
            };
            reader.onerror = (error) => reject(error);
        });
        this._input = undefined;
        this._fileList = undefined;
        this._uploadButton = undefined;
        this._srTextContainer = undefined;
        this.files = [];
        this.error = false;
        this.errorMessages = [];
        this.fileHover = false;
        this.afLabel = _t.form.file_upload;
        this.afLabelDescription = undefined;
        this.afVariation = FormFileUploadVariation.SMALL;
        this.afId = randomIdGenerator('digi-form-file-upload');
        this.afFileTypes = undefined;
        this.afFileMaxSize = 10;
        this.afMaxFiles = undefined;
        this.afName = undefined;
        this.afUploadBtnText = undefined;
        this.afRequired = undefined;
        this.afRequiredText = undefined;
        this.afAnnounceIfOptional = false;
        this.afHeadingFiles = _t.form.file_uploaded_files;
        this.afAnnounceIfOptionalText = undefined;
        this.afFileMaxSizeText = undefined;
        this.afShowThumbnail = false;
        this.afEnablePreview = false;
        this.afValidationText = undefined;
        this.afValidation = FormFileUploadValidation.DISABLED;
        this.afHeadingLevel = FormFileUploadHeadingLevel.H2;
    }
    afValidationTextChange() {
        this.setValidationText();
    }
    breakpointHandler(e) {
        if (e.detail.value) {
            if (e.detail.value === UtilBreakpointObserverBreakpoints.SMALL) {
                this.afVariation = FormFileUploadVariation.SMALL;
            }
            else {
                this.afVariation = this.aforiginalVariation;
            }
        }
    }
    /**
     * Används för att skicka in en validerad fil tillbaks till komponenten. Förväntar sig att filen redan finns i komponenten med status "pending".
     * @en Send a validated file to the component. Expects file to exist in component with status "pending".
     */
    async afMValidateFile(file) {
        if (!this.fileExistInFiles(file)) {
            return;
        }
        this.removeFileFromList(file['id']);
        if (file['status'] !== 'error') {
            /* Måste göra en kopia av filen för att komponenten ska rendera om sig.
             * Annars kan den peka på samma referens och förstår inte att statusen har ändrats.  */
            const copiedFile = new File([file], file.name, { type: file.type });
            copiedFile['id'] = file['id'];
            copiedFile['status'] = file['status'];
            copiedFile['base64'] = await this.toBase64(file);
            this.files = [...this.files, copiedFile];
        }
        else {
            this.validateFile(file);
        }
    }
    /**
     * Få ut alla uppladdade filer
     * @en Get all uploaded files
     */
    async afMGetAllFiles() {
        return this.files;
    }
    /**
     * Hämta ut komponentens validitets-state och felmeddelanden
     * @en Get component validity and error messages
     */
    async afMGetValidationState() {
        return { isValid: !this.error, errorMessages: this.errorMessages };
    }
    /**
     * Importera lista med filer utan att trigga uppladdningsevent. Ett objekt måste innehålla id, status och filen själv.
     * @en Import array with files without triggering upload event. A file object needs to contain an id, status and the file itself.
     */
    async afMImportFiles(files) {
        if (files && files.length > 0) {
            for (const importedFile of files) {
                this.validateFile(importedFile);
            }
        }
        const filesThatArOK = this.errorMessages.length === 0 ? files : this.getFilesThatAreOK(files);
        if (filesThatArOK.length === 0) {
            return;
        }
        this.files = this.files.concat(filesThatArOK);
    }
    async afMGetFormControlElement() {
        return this._input;
    }
    componentWillLoad() {
        this.aforiginalVariation = this.afVariation;
    }
    componentDidLoad() {
        this.afOnReady.emit();
        /* Vid första renderingen så fungerar inte propertyn korrekt om vi inte kallar på setValidationText härifrån.
         * Gissar att det är en tajmin-issue mellan prop och state, men hinner inte gräva i det mer nu.  */
        this.setValidationText();
    }
    get fileMaxSize() {
        const MEGABYTE = 1048576;
        return this.afFileMaxSize * MEGABYTE;
    }
    setValidationText() {
        if (this.afValidationText && this.afValidationText.length > 0) {
            let isDuplicated = false;
            if (this.errorMessages.length > 0) {
                this.errorMessages.forEach((error) => {
                    if (error.message === this.afValidationText) {
                        isDuplicated = true;
                    }
                });
            }
            if (!isDuplicated) {
                this.errorMessages.push({
                    fileName: '',
                    message: this.afValidationText
                });
            }
            this.error = true;
        }
        else {
            this.resetErrors();
        }
    }
    fileExistInFiles(fileToCheck) {
        let exist = false;
        if (this.files.length > 0) {
            this.files.forEach((file) => {
                if (file.name === fileToCheck.name) {
                    exist = true;
                }
            });
        }
        return exist;
    }
    checkAcceptedTypes(file) {
        const acceptedTypes = this.afFileTypes.replace(/\s/g, '').split(',');
        const fileMimeType = file.type;
        const fileNameExtension = file.name
            .split('.')
            .slice(-1)
            .map((item) => '.' + item.toLowerCase())
            .toString();
        return acceptedTypes.some((item) => {
            // Checking against group of mime types
            if (item.includes('/*')) {
                const mimeTypeCategory = item.split('/').slice(0, 1).toString();
                const fileMimeTypeCategory = fileMimeType
                    .split('/')
                    .slice(0, 1)
                    .toString();
                return mimeTypeCategory == fileMimeTypeCategory;
            }
            // Checking against mimetype and extension
            return (item === fileMimeType || item === fileNameExtension || item === '*');
        });
    }
    resetErrors(handleFocus = false) {
        this.error = false;
        this._srTextContainer.textContent = '';
        this.errorMessages = [];
        /* Timeouten behövs för att state och element ska hinna renderas om innan fokus flyttas.
         Vi märkte att det blir problem för hjälpmedel om den inte är på plats.  */
        if (handleFocus) {
            setTimeout(() => {
                this._uploadButton.focus();
            }, 100);
        }
    }
    addErrorMessage(fileName, message) {
        this.errorMessages.push({
            fileName: fileName,
            message: message
        });
    }
    validateFileStatus(file) {
        if (file['status'] &&
            file['status'] === FormValidationMessageVariation.ERROR) {
            const message = file['error']
                ? file['error']
                : _t.form.file_error_unknown_error;
            this.addErrorMessage(file.name, message);
        }
    }
    validateMaxSize(file) {
        if (file.size > this.fileMaxSize) {
            const message = this.afFileMaxSizeText
                ? this.afFileMaxSizeText
                : _t.form.file_error_too_large(file.name, this.afFileMaxSize);
            this.addErrorMessage(file.name, message);
        }
    }
    validateFileType(file) {
        if (!this.checkAcceptedTypes(file)) {
            this.addErrorMessage(file.name, _t.form.file_error_filetype_not_allowed(file.name, this.afFileTypes));
        }
    }
    validateFile(file) {
        this.validateIfFileIsAlreadyUploaded(file);
        this.validateFileStatus(file);
        this.validateMaxSize(file);
        this.validateFileType(file);
        this.error = this.errorMessages.length > 0;
    }
    onCancelFileHandler(e, id) {
        e.preventDefault();
        const fileFromList = this.removeFileFromList(id);
        fileFromList['status'] = 'error';
        fileFromList['error'] = _t.form.file_upload_canceled;
        this.afOnCancelFile.emit(fileFromList);
    }
    removeFileFromList(id) {
        const index = this.getIndexOfFile(id);
        if (index === -1) {
            return;
        }
        const removedFile = this.files[index];
        this.files = [
            ...this.files.slice(0, index),
            ...this.files.slice(index + 1)
        ];
        return removedFile;
    }
    getIndexOfFile(id) {
        const index = this.files.findIndex((file) => file['id'] == id);
        return index;
    }
    getFilesThatAreOK(files) {
        const validFiles = [];
        files.forEach((file) => {
            let isValid = true;
            this.errorMessages.forEach((message) => {
                if (message.fileName === file.name) {
                    isValid = false;
                }
            });
            if (isValid) {
                validFiles.push(file);
            }
        });
        return validFiles;
    }
    validateIfFileIsAlreadyUploaded(file) {
        for (const item of this.files) {
            if (item.name === file.name) {
                this.addErrorMessage(file.name, _t.form.file_error_exists(file.name));
            }
        }
    }
    handleFiles(e) {
        var _a, _b;
        this.resetErrors();
        const fileList = e.dataTransfer ? (_a = e.dataTransfer) === null || _a === void 0 ? void 0 : _a.files : (_b = e.target) === null || _b === void 0 ? void 0 : _b.files;
        const filesToValidate = [];
        Array.from(fileList).forEach((file) => {
            filesToValidate.push(file);
        });
        if (!filesToValidate || filesToValidate.length === 0) {
            return;
        }
        const numberOfFiles = filesToValidate.length + this.files.length;
        if (numberOfFiles > this.afMaxFiles) {
            this.addErrorMessage('', _t.form.file_error_too_many);
            this.error = true;
            return;
        }
        filesToValidate.forEach((file) => {
            this.validateFile(file);
        });
        const filesThatArOK = this.errorMessages.length === 0
            ? filesToValidate
            : this.getFilesThatAreOK(filesToValidate);
        if (filesThatArOK.length === 0) {
            return;
        }
        const formData = new FormData();
        filesThatArOK.forEach((file) => {
            formData.append('file', file);
        });
        for (const obj of formData.entries()) {
            this.addFileStatusAndEmitFiles(obj[1]);
        }
        this._input.value = '';
    }
    onButtonUploadFileHandler(e) {
        e.preventDefault();
        if (!e.target.files)
            return;
        this.handleFiles(e);
    }
    onRemoveFileHandler(e, id) {
        e.preventDefault();
        this.resetErrors();
        const fileToRemove = this.removeFileFromList(id);
        this.afOnRemoveFile.emit(fileToRemove);
        this._input.value = '';
        this.handleFocusAfterFileRemoved();
    }
    handleFocusAfterFileRemoved() {
        /* Timeouten behövs för att state och element ska hinna renderas om innan fokus flyttas.
           Vi märkte att det blir problem för hjälpmedel om den inte är på plats.  */
        setTimeout(() => {
            if (this.files.length > 0) {
                this._fileList.focus();
            }
            else {
                this._uploadButton.focus();
            }
        }, 100);
    }
    emitFile(file) {
        const index = this.getIndexOfFile(file['id']);
        if (this.afValidation === FormFileUploadValidation.ENABLED) {
            this.afOnUploadFile.emit(this.files[index]);
        }
        else {
            this.files[index]['status'] = 'OK';
            this.afOnUploadFile.emit(this.files[index]);
        }
    }
    async addFileStatusAndEmitFiles(file) {
        file['id'] = randomIdGenerator('file');
        file['status'] = 'pending';
        file['base64'] = await this.toBase64(file);
        this.files = [...this.files, file];
        this.emitFile(file);
    }
    handleDrop(e) {
        e.stopPropagation();
        e.preventDefault();
        this.fileHover = false;
        if (e.dataTransfer.files) {
            this.handleFiles(e);
        }
    }
    handleAllowDrop(e) {
        if (this.afVariation === FormFileUploadVariation.SMALL)
            return;
        e.stopPropagation();
        e.preventDefault();
    }
    handleOnDragEnterLeave(e) {
        this.handleAllowDrop(e);
        this.fileHover = !this.fileHover;
    }
    handleInputClick(e) {
        e.stopPropagation();
        this.afShowModal.emit();
        this._input.click();
    }
    getFiletypeAndShortFileName(file) {
        let fileType = null;
        let fileName = file.name;
        const fileExtension = fileName.split('.').pop();
        const fileWithoutExtension = fileName.replace('.' + fileExtension, '');
        const minChars = window.innerWidth < 769 ? 6 : fileName.length;
        const maxChars = window.innerWidth < 769 ? 14 : fileName.length;
        if (String(file['type']).split('/')[0] === 'image') {
            fileType = 'image';
        }
        else if (String(file['type']).split('/')[1] === 'pdf') {
            fileType = 'pdf';
        }
        else {
            fileType = 'default';
        }
        if (fileName.length > minChars) {
            fileName =
                fileWithoutExtension.substring(0, minChars) + '...' + fileExtension;
        }
        else if (fileName.length > maxChars) {
            fileName = fileWithoutExtension.substring(0, 6) + '...' + fileExtension;
        }
        else {
            fileName = file.name;
        }
        return { type: fileType, name: fileName };
    }
    // If its a pdf or an image the file is opened on another tab, any other file formats are downloaded
    async viewUploadedFile(e, file) {
        e.preventDefault();
        if (this.getFiletypeAndShortFileName(file).type === 'image') {
            const w = window.open();
            w.document.write(`<img src="data:${file['type']};base64,${file['base64']}" alt="${file.name}" />`);
            w.document.title = file['name'];
        }
        else if (this.getFiletypeAndShortFileName(file).type === 'pdf') {
            (async () => {
                const pdfstr = await fetch(`data:application/pdf;base64,${file['base64']}`);
                const blobFromFetch = await pdfstr.blob();
                const blob = new Blob([blobFromFetch], { type: 'application/pdf' });
                const blobUrl = URL.createObjectURL(blob);
                setTimeout(() => {
                    window.open(blobUrl, '_blank');
                }, 30);
            })();
        }
        else {
            const fileURL = URL.createObjectURL(file);
            const a = document.createElement('a');
            a.href = fileURL;
            a.target = '_blank';
            a.download = file.name;
            a.click();
        }
    }
    get cssModifiers() {
        return {
            'digi-form-file-upload--small': this.afVariation == 'small',
            'digi-form-file-upload--medium': this.afVariation == 'medium',
            'digi-form-file-upload--large': this.afVariation == 'large',
            'digi-form-file-upload--has-errors': this.errorMessages.length > 0
        };
    }
    renderErrorMessage() {
        if (!this.error) {
            return;
        }
        this.readErrorMessagesToAssistiveTechnologies();
        const showBorder = this.files.length > 0 ? 'with-files' : '';
        return (h("div", { class: 'digi-form-file-upload__error-list-container ' + showBorder }, h("ul", { class: "digi-form-file-upload__error-list", "aria-hidden": "true" }, this.renderErrorMessages()), h("button", { type: "button", "aria-label": _t.form.file_upload_reset_errors_aria_label, class: "digi-form-file-upload__button clear-button hidden-mobile", onClick: () => {
                this.resetErrors(true);
            } }, h("span", null, _t.form.file_upload_reset_errors)), h("button", { type: "button", onClick: () => {
                this.resetErrors(true);
            }, class: "digi-form-file-upload__button clear-button hidden-desktop", "aria-label": _t.form.file_upload_reset_errors_aria_label }, h("digi-icon-x-button-outline", { class: "digi-form-file-upload__button-icon clear-icon", "aria-hidden": "true" }))));
    }
    readErrorMessagesToAssistiveTechnologies() {
        this._srTextContainer.textContent = '';
        const srTexts = this.errorMessages.map((error) => {
            return error.message + ' ';
        });
        /* Timeouten behövs för att state och element ska hinna renderas om innan innehållet ändras.
           Vi märkte att det blir problem för hjälpmedel om den inte är på plats.  */
        setTimeout(() => {
            this._srTextContainer.textContent = srTexts.toString();
        }, 200);
    }
    renderErrorMessages() {
        return this.errorMessages.map((error) => {
            return (h("li", null, h("digi-form-validation-message", { id: "digi-form-file-upload__error", class: "digi-form-file-upload__error", "af-variation": "error" }, error.message)));
        });
    }
    renderPendingFile(file) {
        return (h("div", { class: "digi-form-file-upload__item-pending-container" }, h("span", { class: "info-wrapper" }, h("digi-icon-spinner", { class: "digi-form-file-upload__spinner" }), h("span", { style: { margin: '0' } }, _t.form.file_upload_progress, " ", h("span", { class: "hidden-mobile" }, "|")), h("p", { class: "digi-form-file-upload__item-name-pending hidden-mobile" }, this.getFiletypeAndShortFileName(file).name)), h("span", { class: "button-wrapper" }, h("button", { type: "button", onClick: (e) => this.onCancelFileHandler(e, file['id']), class: "digi-form-file-upload__button digi-form-file-upload__button-abort hidden-mobile", "aria-label": _t.form.file_cancel_upload_long(file.name) }, _t.form.file_cancel_upload), h("button", { type: "button", onClick: (e) => this.onCancelFileHandler(e, file['id']), class: "digi-form-file-upload__button hidden-desktop", "aria-label": _t.form.file_cancel_upload_long(file.name) }, h("digi-icon-x-button-outline", { class: "digi-form-file-upload__button-icon", "aria-hidden": "true" })))));
    }
    renderImageThumbnail(file) {
        if (this.afShowThumbnail) {
            return (h("figure", { class: "digi-form-file-upload__item-text-container-figure", style: { margin: '0' } }, h("img", { "aria-hidden": "true", class: "thumbnail", src: `data:${file['type']};base64,${file['base64']}` }), h("figcaption", { class: "visually-hidden" }, "Miniatyr av ", file.name)));
        }
        return this.renderCheckmark();
    }
    renderCheckmark() {
        return (h("span", { class: "digi-form-file-upload__item-green-check" }, h("digi-icon-check-circle-solid", null)));
    }
    renderPDFThumbnail(file) {
        if (this.afShowThumbnail) {
            return (h("span", { class: `${this.afShowThumbnail ? 'digi-form-file-upload__item-pdf-preview-bis' : null}`, "aria-label": file.name }, h("svg", { style: { scale: '1' }, width: "23.76", height: "32", xmlns: "http://www.w3.org/2000/svg" }, h("path", { d: "M22.888 6.124 17.696.88A2.955 2.955 0 0 0 15.6 0H2.97C1.33.006 0 1.35 0 3.006V29C0 30.657 1.33 32 2.97 32h17.82c1.64 0 2.97-1.343 2.97-3V8.249a3.03 3.03 0 0 0-.872-2.124Zm-2.34 1.88H15.84V3.25l4.709 4.756ZM2.97 29.002V3.006h9.9v6.498c0 .831.662 1.5 1.485 1.5h6.435v17.997H2.97Zm15.481-8.98c-.755-.75-2.908-.544-3.985-.406-1.064-.656-1.775-1.562-2.277-2.893.242-1.006.625-2.537.335-3.5-.26-1.637-2.34-1.474-2.636-.368-.273 1.006-.025 2.406.433 4.193-.619 1.493-1.54 3.499-2.19 4.649-1.238.643-2.909 1.637-3.156 2.887-.204.987 1.609 3.449 4.708-1.95 1.386-.462 2.896-1.031 4.233-1.256 1.17.637 2.537 1.062 3.452 1.062 1.578 0 1.733-1.762 1.083-2.418ZM6.194 24.883c.315-.856 1.516-1.844 1.88-2.187-1.175 1.893-1.88 2.23-1.88 2.187Zm5.049-11.91c.458 0 .414 2.005.111 2.549-.272-.869-.266-2.55-.111-2.55Zm-1.51 8.535c.6-1.056 1.114-2.312 1.528-3.418.514.944 1.17 1.7 1.863 2.219-1.287.268-2.407.818-3.391 1.2Zm8.143-.312s-.31.375-2.308-.488c2.172-.162 2.53.338 2.308.488Z", fill: "var(--digi--color--icon--cta)", "fill-rule": "evenodd" }))));
        }
        return this.renderCheckmark();
    }
    renderThumbnail(file) {
        const fileType = this.getFiletypeAndShortFileName(file).type;
        switch (fileType) {
            case 'pdf':
                return this.renderPDFThumbnail(file);
            case 'image':
                return this.renderImageThumbnail(file);
            default:
                return this.renderCheckmark();
        }
    }
    renderFileName(file) {
        if (this.afEnablePreview) {
            return (h("a", { class: "digi-form-file-upload__item-name", href: "#", onClick: (e) => {
                    this.viewUploadedFile(e, file);
                } }, file.name));
        }
        else {
            return h("span", { class: "digi-form-file-upload__item-name" }, file.name);
        }
    }
    renderOKFile(file) {
        return (h(Fragment, null, h("span", { class: "digi-form-file-upload__item-text-and-thumbnail-container" }, this.renderThumbnail(file), this.renderFileName(file)), h("button", { type: "button", onClick: (e) => this.onRemoveFileHandler(e, file['id']), class: "digi-form-file-upload__button digi-form-file-upload__button--mobile", "aria-label": _t.form.file_remove(file.name) }, h("span", { class: "hidden-mobile" }, _t.form.file_remove()), h("digi-icon-trash", { class: "digi-form-file-upload__button-icon hidden-desktop" }))));
    }
    renderFile(file) {
        switch (file['status']) {
            case 'pending':
                return this.renderPendingFile(file);
            default:
                return this.renderOKFile(file);
        }
    }
    renderFiles() {
        const filesMap = this.files.map((file, index) => {
            {
                return (h("li", { class: "digi-form-file-upload__item-container", key: 'file-' + index }, h("div", { class: "digi-form-file-upload__item" }, h("div", { class: "digi-form-file-upload__item-text-container" }, this.renderFile(file)))));
            }
        });
        return filesMap;
    }
    renderFileContainer() {
        if (this.files.length === 0) {
            return;
        }
        return (h(Fragment, null, h(this.afHeadingLevel, { class: {
                'digi-form-file-upload__files-heading': true,
                'digi-form-file-upload__files-heading--and-errors': this.error
            } }, this.afHeadingFiles), h("ul", { class: "digi-form-file-upload__files-list", tabindex: -1, ref: (el) => {
                this._fileList = el;
            } }, this.renderFiles())));
    }
    render() {
        return (h(Fragment, { key: '3c3b10acd16e7e8df33eb57139a4d841e576a4d6' }, h("digi-util-breakpoint-observer", { key: 'f0cfe2d2962ee2755757ceed6dc2e22c899677e0', onAfOnChange: (e) => this.breakpointHandler(e) }), h("div", { key: '1f356bc476148a1b387025877f7ce5107388b7c5', class: Object.assign({ 'digi-form-file-upload': true }, this.cssModifiers) }, h("digi-form-label", { key: 'b881b2cbc54e3bb58e64874e71c8133bfb48b3d3', afFor: this.afId, afLabel: this.afLabel, afDescription: this.afLabelDescription, afRequired: this.afRequired, afAnnounceIfOptional: this.afAnnounceIfOptional, afRequiredText: this.afRequiredText, afAnnounceIfOptionalText: this.afAnnounceIfOptionalText }), h("div", { key: 'ff17bfc6fa0a50352b3f37863f799e421dc51070', class: {
                'digi-form-file-upload__upload-area': true,
                'digi-form-file-upload__upload-area--hover': this.fileHover
            }, onDrop: (e) => this.handleDrop(e), onDragOver: (e) => this.handleAllowDrop(e), onDragEnter: (e) => this.handleOnDragEnterLeave(e), onDragLeave: (e) => this.handleOnDragEnterLeave(e), onClick: (e) => this.handleInputClick(e) }, this.fileHover &&
            this.afVariation != FormFileUploadVariation.SMALL && (h("div", { key: '62df2861282318e64d22706e8ea3c8b6c0c1a21b', class: "digi-form-file-upload__upload-area-overlay" })), h("div", { key: '6a4ad53626f507b371a1279f77b8076eb09ed844', class: "digi-form-file-upload__text-area" }, h("button", { key: '581c5393e78277ff20a319c6e2da8da6383379e9', type: "button", ref: (el) => {
                this._uploadButton = el;
            }, onClick: (e) => this.handleInputClick(e), class: "digi-form-file-upload__button hidden_mobile", style: {
                margin: '0'
            } }, h("digi-icon-paperclip", { key: 'c636d31cfc7cd9723f7e0b0c1fda4055da43f7b3', "aria-hidden": "true", class: "digi-form-file-upload__button-icon paper-clip", slot: "icon" }), this.afUploadBtnText
            ? this.afUploadBtnText
            : _t.form.file_choose), h("input", { key: '5588622cf835074d7dc0efa97a99d5e21a1ccfee', ref: (el) => {
                this._input = el;
            }, onChange: (e) => this.onButtonUploadFileHandler(e), class: "digi-form-file-upload__input", multiple: true, type: "file", id: this.afId, accept: this.afFileTypes, name: this.afName ? this.afName : null, required: this.afRequired ? this.afRequired : null, onDrop: (e) => this.handleDrop(e), onDragOver: (e) => this.handleAllowDrop(e), "aria-errormessage": "digi-form-file-upload__error", "aria-describedBy": "digi-form-file-upload__error" }), h("span", { key: 'c5d84449ecdd6a0ffacc044bcfdc68ee6eac1b05' }, this.afVariation !== FormFileUploadVariation.SMALL &&
            _t.form.file_dropzone))), h("p", { key: 'dc43de81b8217c4ce6befe4034adb950d0faf7b3', class: "visually-hidden", role: "alert", "aria-atomic": "true", ref: (el) => {
                this._srTextContainer = el;
            } }), (this.files.length > 0 || this.error) && (h("div", { key: '820daa5debbee48feb5236c125abb22352a8a707', class: "digi-form-file-upload__files" }, this.renderErrorMessage(), this.renderFileContainer())))));
    }
    static get is() { return "digi-form-file-upload"; }
    static get encapsulation() { return "scoped"; }
    static get originalStyleUrls() {
        return {
            "$": ["form-file-upload.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["form-file-upload.css"]
        };
    }
    static get properties() {
        return {
            "afLabel": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "The label text. Required field."
                        }],
                    "text": "Texten till label-elementet. Obligatoriskt f\u00E4lt."
                },
                "getter": false,
                "setter": false,
                "attribute": "af-label",
                "reflect": false,
                "defaultValue": "_t.form.file_upload"
            },
            "afLabelDescription": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "A description text"
                        }],
                    "text": "Valfri beskrivande text"
                },
                "getter": false,
                "setter": false,
                "attribute": "af-label-description",
                "reflect": false
            },
            "afVariation": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "FormFileUploadVariation",
                    "resolved": "FormFileUploadVariation.LARGE | FormFileUploadVariation.MEDIUM | FormFileUploadVariation.SMALL",
                    "references": {
                        "FormFileUploadVariation": {
                            "location": "import",
                            "path": "./form-file-upload-variation.enum",
                            "id": "src/components/_form/form-file-upload/form-file-upload-variation.enum.ts::FormFileUploadVariation"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Set input variation 'small', 'medium' or 'large'. On a mobile screen the variation will be automatically set to 'small'."
                        }],
                    "text": "S\u00E4tter variant. Kan vara 'small', 'medium' eller 'large'. Oberoende p\u00E5 satt storlek s\u00E5 kommer komponenten bli 'small' p\u00E5 mobilsk\u00E4rmar."
                },
                "getter": false,
                "setter": false,
                "attribute": "af-variation",
                "reflect": false,
                "defaultValue": "FormFileUploadVariation.SMALL"
            },
            "afId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Input id attribute. Defaults to random string."
                        }],
                    "text": "S\u00E4tter attributet 'id'. Om inget v\u00E4ljs s\u00E5 skapas ett slumpm\u00E4ssigt id."
                },
                "getter": false,
                "setter": false,
                "attribute": "af-id",
                "reflect": false,
                "defaultValue": "randomIdGenerator('digi-form-file-upload')"
            },
            "afFileTypes": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Set input field's accept attribute. Use this to limit accepted file types."
                        }],
                    "text": "S\u00E4tter attributet 'accept'. Anv\u00E4nd f\u00F6r att limitera accepterade filtyper"
                },
                "getter": false,
                "setter": false,
                "attribute": "af-file-types",
                "reflect": false
            },
            "afFileMaxSize": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Set file max size in MB"
                        }],
                    "text": "S\u00E4tter en maximal filstorlek i MB, 10MB \u00E4r standard."
                },
                "getter": false,
                "setter": false,
                "attribute": "af-file-max-size",
                "reflect": false,
                "defaultValue": "10"
            },
            "afMaxFiles": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Set maximum number of upload files"
                        }],
                    "text": "S\u00E4tter maximalt antal filer som kan laddas upp"
                },
                "getter": false,
                "setter": false,
                "attribute": "af-max-files",
                "reflect": false
            },
            "afName": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Input name attribute"
                        }],
                    "text": "S\u00E4tter attributet 'name'."
                },
                "getter": false,
                "setter": false,
                "attribute": "af-name",
                "reflect": false
            },
            "afUploadBtnText": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Set upload buttons text"
                        }],
                    "text": "S\u00E4tter ladda upp knappens text."
                },
                "getter": false,
                "setter": false,
                "attribute": "af-upload-btn-text",
                "reflect": false
            },
            "afRequired": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Input required attribute"
                        }],
                    "text": "S\u00E4tter attributet 'required'."
                },
                "getter": false,
                "setter": false,
                "attribute": "af-required",
                "reflect": false
            },
            "afRequiredText": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Set text for afRequired."
                        }],
                    "text": "S\u00E4tter text f\u00F6r afRequired."
                },
                "getter": false,
                "setter": false,
                "attribute": "af-required-text",
                "reflect": false
            },
            "afAnnounceIfOptional": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Set this to true if the form contains more required fields than optional fields."
                        }],
                    "text": "S\u00E4tt denna till true om formul\u00E4ret inneh\u00E5ller fler obligatoriska f\u00E4lt \u00E4n valfria."
                },
                "getter": false,
                "setter": false,
                "attribute": "af-announce-if-optional",
                "reflect": false,
                "defaultValue": "false"
            },
            "afHeadingFiles": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Set heading for uploaded files."
                        }],
                    "text": "S\u00E4tt rubrik f\u00F6r uppladdade filer."
                },
                "getter": false,
                "setter": false,
                "attribute": "af-heading-files",
                "reflect": false,
                "defaultValue": "_t.form.file_uploaded_files"
            },
            "afAnnounceIfOptionalText": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Set text for afAnnounceIfOptional."
                        }],
                    "text": "S\u00E4tter text f\u00F6r afAnnounceIfOptional."
                },
                "getter": false,
                "setter": false,
                "attribute": "af-announce-if-optional-text",
                "reflect": false
            },
            "afFileMaxSizeText": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Set text for warning on file size exceeded."
                        }],
                    "text": "S\u00E4tter text vid varning om \u00F6verskriden filstorlek."
                },
                "getter": false,
                "setter": false,
                "attribute": "af-file-max-size-text",
                "reflect": false
            },
            "afShowThumbnail": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Shows thumbnail."
                        }],
                    "text": "Visar miniatyrbild/ikon p\u00E5 uppladdade filer."
                },
                "getter": false,
                "setter": false,
                "attribute": "af-show-thumbnail",
                "reflect": false,
                "defaultValue": "false"
            },
            "afEnablePreview": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Activates preview of uploaded files."
                        }],
                    "text": "Aktiverar f\u00F6rhandsgranskning."
                },
                "getter": false,
                "setter": false,
                "attribute": "af-enable-preview",
                "reflect": false,
                "defaultValue": "false"
            },
            "afValidationText": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Set validation message"
                        }],
                    "text": "S\u00E4tter valideringsmeddelande. Kan exempelvis anv\u00E4ndas f\u00F6r att f\u00F6rtydliga obligatoriskt f\u00E4lt."
                },
                "getter": false,
                "setter": false,
                "attribute": "af-validation-text",
                "reflect": false
            },
            "afValidation": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "FormFileUploadValidation",
                    "resolved": "FormFileUploadValidation.DISABLED | FormFileUploadValidation.ENABLED",
                    "references": {
                        "FormFileUploadValidation": {
                            "location": "import",
                            "path": "./form-file-upload-validation.enum",
                            "id": "src/components/_form/form-file-upload/form-file-upload-validation.enum.ts::FormFileUploadValidation"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Set antivirus scan status. Enable is default."
                        }],
                    "text": "S\u00E4tter antivirus scan status. Kan vara 'enable' eller 'disabled'."
                },
                "getter": false,
                "setter": false,
                "attribute": "af-validation",
                "reflect": false,
                "defaultValue": "FormFileUploadValidation.DISABLED"
            },
            "afHeadingLevel": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "FormFileUploadHeadingLevel",
                    "resolved": "FormFileUploadHeadingLevel.H1 | FormFileUploadHeadingLevel.H2 | FormFileUploadHeadingLevel.H3 | FormFileUploadHeadingLevel.H4 | FormFileUploadHeadingLevel.H5 | FormFileUploadHeadingLevel.H6",
                    "references": {
                        "FormFileUploadHeadingLevel": {
                            "location": "import",
                            "path": "./form-file-upload-heading-level.enum",
                            "id": "src/components/_form/form-file-upload/form-file-upload-heading-level.enum.ts::FormFileUploadHeadingLevel"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Set heading level. Default is 'h2'"
                        }],
                    "text": "S\u00E4tt rubrikens vikt. 'h2' \u00E4r f\u00F6rvalt."
                },
                "getter": false,
                "setter": false,
                "attribute": "af-heading-level",
                "reflect": false,
                "defaultValue": "FormFileUploadHeadingLevel.H2"
            }
        };
    }
    static get states() {
        return {
            "_input": {},
            "_fileList": {},
            "_uploadButton": {},
            "_srTextContainer": {},
            "files": {},
            "error": {},
            "errorMessages": {},
            "fileHover": {}
        };
    }
    static get events() {
        return [{
                "method": "afOnUploadFile",
                "name": "afOnUploadFile",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Emits file on upload"
                        }],
                    "text": "S\u00E4nder ut fil som h\u00E5ller p\u00E5 att laddas upp, eller som har laddats upp - beroende p\u00E5 afValidation-inst\u00E4llning"
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "afOnRemoveFile",
                "name": "afOnRemoveFile",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Emits which file that was deleted."
                        }],
                    "text": "S\u00E4nder ut vilken fil som tagits bort"
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "afOnCancelFile",
                "name": "afOnCancelFile",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "Emits which file that was canceled"
                        }],
                    "text": "S\u00E4nder ut den fil vars uppladdning avbrutits"
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "afOnReady",
                "name": "afOnReady",
                "bubbles": false,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "When the component and slots are loaded and initialized this event will trigger."
                        }],
                    "text": "N\u00E4r komponenten och slotsen \u00E4r laddade och initierade s\u00E5 skickas detta eventet."
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "afShowModal",
                "name": "afShowModal",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [{
                            "name": "en",
                            "text": "When the file selection modal is activated"
                        }],
                    "text": "N\u00E4r f\u00F6nstret f\u00F6r att v\u00E4lja filer \u00F6ppnas"
                },
                "complexType": {
                    "original": "void",
                    "resolved": "void",
                    "references": {}
                }
            }];
    }
    static get methods() {
        return {
            "afMValidateFile": {
                "complexType": {
                    "signature": "(file: File) => Promise<void>",
                    "parameters": [{
                            "name": "file",
                            "type": "File",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        },
                        "File": {
                            "location": "global",
                            "id": "global::File"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "Anv\u00E4nds f\u00F6r att skicka in en validerad fil tillbaks till komponenten. F\u00F6rv\u00E4ntar sig att filen redan finns i komponenten med status \"pending\".",
                    "tags": [{
                            "name": "en",
                            "text": "Send a validated file to the component. Expects file to exist in component with status \"pending\"."
                        }]
                }
            },
            "afMGetAllFiles": {
                "complexType": {
                    "signature": "() => Promise<File[]>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        },
                        "File": {
                            "location": "global",
                            "id": "global::File"
                        }
                    },
                    "return": "Promise<File[]>"
                },
                "docs": {
                    "text": "F\u00E5 ut alla uppladdade filer",
                    "tags": [{
                            "name": "en",
                            "text": "Get all uploaded files"
                        }]
                }
            },
            "afMGetValidationState": {
                "complexType": {
                    "signature": "() => Promise<{ isValid: boolean; errorMessages: Array<FormFileUploadErrorMessage>; }>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        },
                        "Array": {
                            "location": "global",
                            "id": "global::Array"
                        },
                        "FormFileUploadErrorMessage": {
                            "location": "import",
                            "path": "./form-file-upload-error-messages.type",
                            "id": "src/components/_form/form-file-upload/form-file-upload-error-messages.type.ts::FormFileUploadErrorMessage"
                        }
                    },
                    "return": "Promise<{ isValid: boolean; errorMessages: FormFileUploadErrorMessage[]; }>"
                },
                "docs": {
                    "text": "H\u00E4mta ut komponentens validitets-state och felmeddelanden",
                    "tags": [{
                            "name": "en",
                            "text": "Get component validity and error messages"
                        }]
                }
            },
            "afMImportFiles": {
                "complexType": {
                    "signature": "(files: File[]) => Promise<void>",
                    "parameters": [{
                            "name": "files",
                            "type": "File[]",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        },
                        "File": {
                            "location": "global",
                            "id": "global::File"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "Importera lista med filer utan att trigga uppladdningsevent. Ett objekt m\u00E5ste inneh\u00E5lla id, status och filen sj\u00E4lv.",
                    "tags": [{
                            "name": "en",
                            "text": "Import array with files without triggering upload event. A file object needs to contain an id, status and the file itself."
                        }]
                }
            },
            "afMGetFormControlElement": {
                "complexType": {
                    "signature": "() => Promise<HTMLInputElement>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        },
                        "HTMLInputElement": {
                            "location": "global",
                            "id": "global::HTMLInputElement"
                        }
                    },
                    "return": "Promise<HTMLInputElement>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            }
        };
    }
    static get elementRef() { return "hostElement"; }
    static get watchers() {
        return [{
                "propName": "afValidationText",
                "methodName": "afValidationTextChange"
            }];
    }
}
