import { h, r as registerInstance, c as createEvent, H as Host, g as getElement } from './index-BdVwMG9u.js';
import { _ as __decorate, a as __metadata } from './tslib.es6-dfXERft2.js';
import { a as ariaBooleanToString } from './aria-DBsOHTWj.js';
import { a as areArraysEqual } from './array-CDfSqLEo.js';
import { d as defaultBalAriaForm } from './form-FCLKfv6B.js';
import { s as stopEventBubbling, i as inputHandleHostClick, a as inputHandleFocus, b as inputHandleBlur, c as inputSetFocus, d as inputSetBlur } from './form-input-DYvzaBlM.js';
import { L as Logger } from './log-CwssmmaV.js';
import { g as getDefaultExportFromCjs } from './_commonjsHelpers-BFTU3MAI.js';
import { B as BEM } from './bem-ByiN-QjD.js';
import { F as FileUploadRejectionReason } from './bal-file-upload.type-rBUN7c88.js';
import './index-zWZxKBfo.js';
import './index-B4k_dH6V.js';
import './helpers-BNj87EbG.js';
import './browser-B1u-Mq75.js';
import './config.utils-B7jugjyM.js';

var lib = {};

var spec = {};

var hasRequiredSpec;

function requireSpec () {
	if (hasRequiredSpec) return spec;
	hasRequiredSpec = 1;
	Object.defineProperty(spec, "__esModule", { value: true });
	var si = { radix: 1e3, unit: ['b', 'kb', 'Mb', 'Gb', 'Tb', 'Pb', 'Eb', 'Zb', 'Yb'] };
	var iec = { radix: 1024, unit: ['b', 'Kib', 'Mib', 'Gib', 'Tib', 'Pib', 'Eib', 'Zib', 'Yib'] };
	var jedec = { radix: 1024, unit: ['b', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb', 'Eb', 'Zb', 'Yb'] };
	spec.SPECS = {
	    si: si,
	    iec: iec,
	    jedec: jedec,
	};
	
	return spec;
}

var hasRequiredLib;

function requireLib () {
	if (hasRequiredLib) return lib;
	hasRequiredLib = 1;
	Object.defineProperty(lib, "__esModule", { value: true });
	var spec_1 = requireSpec();
	/**
	 * file size
	 * @param bytes
	 * @param fixed
	 * @param spec
	 */
	function default_1(bytes, fixed, spec) {
	    if (fixed === void 0) { fixed = 1; }
	    bytes = Math.abs(bytes);
	    var _a = spec_1.SPECS[spec] || spec_1.SPECS['jedec'], radix = _a.radix, unit = _a.unit;
	    var loop = 0;
	    // calculate
	    while (bytes >= radix) {
	        bytes /= radix;
	        ++loop;
	    }
	    return bytes.toFixed(fixed) + " " + unit[loop];
	}
	lib.default = default_1;
	
	return lib;
}

var libExports = requireLib();
var fileSize = /*@__PURE__*/getDefaultExportFromCjs(libExports);

const bemListEl = BEM.block('file-upload').element('list');
const FileListComponent = ({ files, disabled, subTitle, onRemoveFile, }) => {
    return (h("bal-card", { class: Object.assign({}, bemListEl.class()), flat: true }, h("bal-list", { disabled: disabled, border: true, size: "large" }, files.map((file, index) => (h("bal-list-item", { key: file.name, disabled: disabled }, h("bal-list-item-icon", null, h("bal-icon", { name: "document" })), h("bal-list-item-content", null, h("bal-list-item-title", null, file.name), h("bal-list-item-subtitle", null, subTitle ? subTitle(file) : fileSize(file.size))), h("bal-list-item-icon", { right: true, class: {
            'file-remove': true,
        } }, h("button", { class: "button is-square is-danger", disabled: disabled, onClick: event => onRemoveFile(event, index) }, h("bal-icon", { name: "trash", color: disabled ? 'grey' : 'danger' })))))))));
};

/**
 * FileList Utils
 * -------------------------------
 * Utils to work with the FileList object. Unfortunately, jsdom does not
 * support the DataTransfer API, so we were not able to write any
 * unit test for it.
 */
const toFileArray = (list) => {
    return Array.from(list ? list : []);
};
const toFileList = (files) => {
    const dataTransfer = new DataTransfer();
    if (files && files.length > 0) {
        files.forEach(file => dataTransfer.items.add(file));
    }
    return dataTransfer.files;
};

const validateFileArray = (state, files, fileOptions) => {
    const validFiles = [];
    const newState = [...state];
    const invalidFiles = [];
    for (let index = 0; index < files.length; index++) {
        const file = files[index];
        if (file) {
            const reasons = [];
            if (fileOptions.accept && fileOptions.accept.split(' ').join('').split(',').indexOf(file.type) === -1) {
                reasons.push(FileUploadRejectionReason.BAD_EXTENSION);
            }
            if (fileOptions.maxFileSize !== undefined && file.size > fileOptions.maxFileSize) {
                reasons.push(FileUploadRejectionReason.FILE_TOO_BIG);
            }
            const stateBundleSize = newState.map(f => f.size).reduce((a, b) => a + b, 0);
            const bundleSize = stateBundleSize + file.size;
            if (fileOptions.maxBundleSize !== undefined && bundleSize > fileOptions.maxBundleSize) {
                reasons.push(FileUploadRejectionReason.FILE_SIZE_SUM_TOO_BIG);
            }
            const amountOfFiles = newState.length + 1;
            if (fileOptions.maxFiles !== undefined && amountOfFiles > fileOptions.maxFiles) {
                reasons.push(FileUploadRejectionReason.TOO_MANY_FILES);
            }
            const areFilesEqual = (fileA, fileB) => fileA.size === fileB.size &&
                fileA.name === fileB.name &&
                fileA.type === fileB.type &&
                fileA.lastModified === fileB.lastModified;
            const duplicatedFiles = state.filter(f => areFilesEqual(f, file));
            if (duplicatedFiles.length > 0) {
                reasons.push(FileUploadRejectionReason.DUPLICATED_FILE);
            }
            if (reasons.length > 0) {
                invalidFiles.push({ file, reasons });
            }
            else {
                newState.push(file);
                validFiles.push(file);
            }
        }
    }
    return {
        validFiles: validFiles,
        invalidFiles: invalidFiles,
    };
};

const balFileUploadCss = ".bal-file-upload{display:block;position:static;width:100%}.bal-file-upload .file-label{word-break:break-word;white-space:normal}.bal-file-upload .bal-heading{word-break:break-all}.bal-file-upload__card{margin-top:var(--bal-space-normal)}.bal-file-upload__list{padding:0 !important}";

const FileUpload = class {
    constructor(hostRef) {
        registerInstance(this, hostRef);
        this.balChange = createEvent(this, "balChange");
        this.balFilesAdded = createEvent(this, "balFilesAdded");
        this.balFilesRemoved = createEvent(this, "balFilesRemoved");
        this.balRejectedFile = createEvent(this, "balRejectedFile");
        this.balInputClick = createEvent(this, "balInputClick");
        this.balBlur = createEvent(this, "balBlur");
        this.balFocus = createEvent(this, "balFocus");
        this.fileUploadId = `bal-file-upload-${FileUploadIds++}`;
        this.files = [];
        this.focused = false;
        this.ariaForm = defaultBalAriaForm;
        /**
         * PUBLIC PROPERTY API
         * ------------------------------------------------------
         */
        /**
         * The name of the control, which is submitted with the form data.
         */
        this.name = this.fileUploadId;
        /**
         * Input value.
         */
        this.value = [];
        this.initialValue = this.value || [];
        /**
         * Label of the drop area.
         */
        this.label = 'Choose or drop a file...';
        /**
         * If `true` multiple file upload is possible.
         */
        this.multiple = true;
        /**
         * If `true`, the element is not mutable, focusable, or even submitted with the form. The user can neither edit nor focus on the control, nor its form control descendants.
         */
        this.disabled = false;
        /**
         * If `true` the element can not mutated, meaning the user can not edit the control.
         */
        this.readonly = false;
        /**
         * If `true` the file upload is disabled and shows a spinner
         */
        this.loading = false;
        /**
         * If `true`, the user must fill in a value before submitting a form.
         */
        this.required = false;
        /**
         * If `true` below the drop-down area it generates a file list.
         */
        this.hasFileList = true;
        /**
         * If `true` the component gets a invalid style.
         */
        this.invalid = false;
        /**
         * If `true`, in Angular reactive forms the control will not be set invalid
         */
        this.autoInvalidOff = false;
        /**
         * PRIVATE METHODS
         * ------------------------------------------------------
         */
        this.addEventListenerDragAndDrop = () => {
            if (this.labelEl) {
                this.labelEl.addEventListener('dragenter', this.onDragenter, false);
                this.labelEl.addEventListener('dragover', this.onDragover, false);
                this.labelEl.addEventListener('drop', this.onDrop, false);
            }
        };
        this.removeEventListenerDragAndDrop = () => {
            if (this.labelEl) {
                this.labelEl.removeEventListener('dragenter', this.onDragenter, false);
                this.labelEl.removeEventListener('dragover', this.onDragover, false);
                this.labelEl.removeEventListener('drop', this.onDrop, false);
            }
        };
        this.handleFiles = (fileList) => {
            const files = toFileArray(fileList);
            const validatedFiles = validateFileArray(this.files, files, {
                accept: this.accept,
                maxFileSize: this.maxFileSize,
                maxBundleSize: this.maxBundleSize,
                maxFiles: this.maxFiles,
            });
            if (validatedFiles.invalidFiles.length > 0) {
                validatedFiles.invalidFiles.forEach(file => this.balRejectedFile.emit(file));
            }
            if (validatedFiles.validFiles.length > 0) {
                this.files = [...this.files, ...validatedFiles.validFiles];
                this.balChange.emit(this.files);
                this.balFilesAdded.emit(validatedFiles.validFiles);
            }
            this.updateFileInput();
        };
        this.updateFileInput = () => {
            var _a;
            if ((_a = this.nativeInput) === null || _a === void 0 ? void 0 : _a.files) {
                this.nativeInput.files = toFileList(this.files);
            }
        };
        /**
         * HANDLERS
         * ------------------------------------------------------
         */
        this.onDragenter = (ev) => {
            stopEventBubbling(ev);
        };
        this.onDragover = (ev) => {
            stopEventBubbling(ev);
        };
        this.onDrop = (ev) => {
            stopEventBubbling(ev);
            if (!this.disabled && !this.readonly && !this.loading) {
                const dataTransfer = ev.dataTransfer;
                if (dataTransfer) {
                    this.handleFiles(dataTransfer.files);
                }
            }
        };
        this.onInputChange = () => {
            var _a;
            if (!this.disabled && !this.readonly && !this.loading) {
                if ((_a = this.nativeInput) === null || _a === void 0 ? void 0 : _a.files) {
                    this.handleFiles(this.nativeInput.files);
                }
            }
        };
        this.onRemoveFile = (ev, index) => {
            stopEventBubbling(ev);
            if (index >= 0 && index < this.files.length) {
                const files = this.files;
                const removedFiles = files.splice(index, 1);
                this.balFilesRemoved.emit(removedFiles);
                this.files = [...files];
                this.balChange.emit(this.files);
                this.updateFileInput();
            }
        };
        this.onHostClick = (ev) => inputHandleHostClick(this, ev);
        this.onInputFocus = (ev) => inputHandleFocus(this, ev);
        this.onInputBlur = (ev) => inputHandleBlur(this, ev);
        this.onInputClick = (ev) => {
            if (this.nativeInput && !this.disabled && !this.readonly && !this.loading) {
                this.nativeInput.value = '';
            }
            this.balInputClick.emit(ev);
        };
    }
    createLogger(log) {
        this.log = log;
    }
    onValueChange() {
        if (!areArraysEqual(this.files, this.value)) {
            this.files = this.value;
        }
    }
    /**
     * LIFECYCLE
     * ------------------------------------------------------
     */
    componentWillLoad() {
        this.onValueChange();
    }
    connectedCallback() {
        this.initialValue = this.value || [];
        this.addEventListenerDragAndDrop();
    }
    componentDidLoad() {
        this.addEventListenerDragAndDrop();
    }
    disconnectedCallback() {
        this.removeEventListenerDragAndDrop();
    }
    resetHandler(ev) {
        const formElement = ev.target;
        if (formElement === null || formElement === void 0 ? void 0 : formElement.contains(this.el)) {
            this.files = [...this.initialValue];
            clearTimeout(this.resetHandlerTimer);
            this.resetHandlerTimer = setTimeout(() => {
                if (this.nativeInput) {
                    this.nativeInput.files = toFileList(this.initialValue);
                }
            });
        }
    }
    /**
     * PUBLIC METHODS
     * ------------------------------------------------------
     */
    /**
     * Sets the file list to an empty list
     */
    async clear() {
        this.files = [];
        this.updateFileInput();
    }
    /**
     * Sets focus on the native `input`. Use this method instead of the global
     * `input.focus()`.
     */
    async setFocus() {
        inputSetFocus(this);
    }
    /**
     * Sets blur on the native `input`. Use this method instead of the global
     * `input.blur()`.
     * @internal
     */
    async setBlur() {
        inputSetBlur(this);
    }
    /**
     * Returns the native `<input>` element used under the hood.
     */
    getInputElement() {
        return Promise.resolve(this.nativeInput);
    }
    /**
     * @internal
     */
    async setAriaForm(ariaForm) {
        this.ariaForm = Object.assign({}, ariaForm);
    }
    /**
     * RENDER
     * ------------------------------------------------------
     */
    render() {
        const id = this.ariaForm.controlId || this.fileUploadId;
        return (h(Host, { key: '777b6af9407be7027865f204a05be3b51977a8a7', onClick: this.onHostClick, "aria-disabled": ariaBooleanToString(this.disabled), class: {
                'bal-file-upload': true,
            } }, h("div", { key: 'a5a40cd9aa548183c4f0feaab16a30ac504da6c7', class: {
                'file': true,
                'is-disabled': this.disabled || this.readonly || this.loading,
                'is-danger': this.invalid,
            } }, h("label", { key: 'ed88786390952890387e357fd8d7f8e6a356fb02', htmlFor: id, ref: el => (this.labelEl = el), class: {
                'file-label': true,
                'is-disabled': this.disabled || this.loading || this.readonly,
            } }, h("input", { key: '79bcf9f330b894a80dbe44b30b99bb631aad9f6f', class: "file-input", type: "file", id: id, "aria-labelledby": this.ariaForm.labelId, "aria-describedby": this.ariaForm.messageId, "aria-invalid": this.invalid === true ? 'true' : 'false', "aria-disabled": ariaBooleanToString(this.disabled), name: this.name, multiple: this.multiple, disabled: this.disabled || this.loading || this.readonly, readonly: this.readonly, required: this.required, accept: this.accept, onClick: this.onInputClick, onChange: this.onInputChange, onFocus: this.onInputFocus, onBlur: this.onInputBlur, ref: el => (this.nativeInput = el), "data-testid": "bal-file-upload-input" }), this.loading ? (h("span", { class: "file-cta" }, h("bal-spinner", null))) : (h("span", { class: "file-cta" }, h("span", { class: "file-icon" }, h("bal-icon", { name: "upload", size: "medium", color: this.disabled || this.loading || this.readonly ? 'grey-light' : this.invalid ? 'danger' : 'blue' })), h("span", { class: "file-label", "data-testid": "bal-file-upload-label" }, this.label))))), this.hasFileList && this.files.length > 0 ? (h(FileListComponent, { files: this.files, disabled: this.disabled || this.readonly || this.loading, subTitle: this.subTitle, onRemoveFile: this.onRemoveFile })) : ('')));
    }
    get el() { return getElement(this); }
    static get watchers() { return {
        "value": ["onValueChange"]
    }; }
};
__decorate([
    Logger('bal-file-upload'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Function]),
    __metadata("design:returntype", void 0)
], FileUpload.prototype, "createLogger", null);
let FileUploadIds = 0;
FileUpload.style = balFileUploadCss;

export { FileUpload as bal_file_upload };
