// #region Imports
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;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { HTMLElementEventEmitter } from '@breadstone/mosaik-elements';
import { RendererServiceLocator } from '../../../../Dom/Renderer';
import { Emit } from '../../../../events/Decorators/EmitDecorator';
import { Listen } from '../../../../events/Decorators/ListenDecorator';
import { IntlController } from '../../../../Intl/IntlController';
import { Appearanceable } from '../../../Behaviors/Appearanceable';
import { Disableable } from '../../../Behaviors/Disableable';
import { Invalidable } from '../../../Behaviors/Invalidable';
import { Themeable } from '../../../Behaviors/Themeable';
import { Valueable } from '../../../Behaviors/Valueable';
import { Variantable } from '../../../Behaviors/Variantable';
import { Attribute } from '../../../Decorators/AttributeDecorator';
import { Component } from '../../../Decorators/ComponentDecorator';
import { Property } from '../../../Decorators/PropertyDecorator';
import { FileUploadView } from '../../../Types/FileUploadView';
import { CustomElement } from '../../Abstracts/CustomElement';
import { ButtonElement } from '../../Buttons/Button/ButtonElement';
import { CardElement } from '../../Grouping/Card/CardElement';
import { ChipElement } from '../../Media/Chip/ChipElement';
import { DropZoneElement } from '../../Primitives/DropZone/DropZoneElement';
import { ListElement } from '../../Selectors/List/ListElement';
import { TableElement } from '../../Selectors/Table/TableElement';
import { FilePickerElement } from './FilePickerElement';
import { fileUploadElementTemplate } from './FileUploadElementTemplate';
import { FileUploadItemElement } from './FileUploadItemElement';
import { FileUploadElementIntl } from './Intl/FileUploadElementIntl';
import { IFileInfo } from './Models/Interfaces/IFileInfo';
import { fileUploadElementCosmopolitanStyle } from './Themes/FileUploadElement.Cosmopolitan';
import { fileUploadElementJoyStyle } from './Themes/FileUploadElement.Joy';
import { fileUploadElementMemphisStyle } from './Themes/FileUploadElement.Memphis';
// #endregion
/**
 * File Upload - A comprehensive file upload control with drag-and-drop support and multiple view modes.
 *
 * @description
 * The File Upload component provides a complete file upload workflow with drag-and-drop functionality,
 * multiple view modes (list, table, card), upload progress tracking, and extensive customization options.
 * It supports single and multiple file selection, file type restrictions, size validation, custom upload
 * strategies, and comprehensive file management features. The component handles file selection via dialog
 * or drag-and-drop, displays upload progress, provides error handling and retry mechanisms, and offers
 * different visual representations for uploaded files. Features include file preview capabilities,
 * batch operations, upload resumption, and integration with various backend services. Perfect for
 * document management systems, media upload interfaces, form attachments, and any application requiring
 * robust file handling capabilities.
 *
 * @name File Upload
 * @element mosaik-file-upload
 * @category Inputs
 *
 * @slot - Default slot for custom UI elements like buttons or instructions.
 *
 * @csspart dropZone - The drag-and-drop zone container.
 * @csspart fileList - The container for file list display.
 * @csspart fileItem - Individual file items in the list.
 * @csspart uploadButton - The file selection button.
 * @csspart progressIndicator - The upload progress display.
 *
 * @cssprop {Color} --file-upload-background-color - The background color.
 * @cssprop {Color} --file-upload-border-color - The border color.
 * @cssprop {String} --file-upload-border-radius - The border radius.
 * @cssprop {String} --file-upload-border-style - The border style.
 * @cssprop {String} --file-upload-border-width - The border width.
 * @cssprop {Color} --file-upload-foreground-color - The foreground color.
 * @cssprop {String} --file-upload-shadow - The shadow.
 *
 * @dependency mosaik-drop-zone - Used for drag-and-drop functionality.
 * @dependency mosaik-file-picker - Used for file selection dialog.
 * @dependency mosaik-button - Used for upload buttons.
 * @dependency mosaik-card - Used for card view mode.
 * @dependency mosaik-chip - Used for file tags.
 * @dependency mosaik-list - Used for list view mode.
 * @dependency mosaik-table - Used for table view mode.
 * @dependency mosaik-file-upload-item - Used for individual file items.
 *
 * @fires fileAdded {FileAddEvent} - Fired when a file is added to the upload list.
 * @fires fileRemoved {FileRemoveEvent} - Fired when a file is removed from the upload list.
 * @fires fileFailed {FileErrorEvent} - Fired when a file upload fails.
 * @fires filesChanged {FilesChangedEvent} - Fired when the set of files has changed.
 *
 * @example
 * ```html
 * <mosaik-file-upload
 *   multiple
 *   accept="image/*"
 *   placeholder="Drop images here or click to browse">
 * </mosaik-file-upload>
 * ```
 *
 * @example
 * ```html
 * <mosaik-file-upload
 *   view="table"
 *   max-size="10MB"
 *   auto-upload="false">
 * </mosaik-file-upload>
 * ```
 *
 * @public
 */
let FileUploadElement = class FileUploadElement extends Themeable(Disableable(Appearanceable(Variantable(Invalidable(Valueable(CustomElement)))))) {
    // #region Fields
    _fileAdded;
    _fileRemoved;
    _fileFailed;
    _filesChanged;
    _intl;
    _inputElement;
    _autoUpload;
    _view;
    _multiple;
    _directory;
    _accept;
    _strategy;
    _value;
    _placeholder;
    _maxSize;
    _isDragging;
    // #endregion
    // #region Ctor
    /**
     * @public
     */
    constructor() {
        super();
        this._intl = new IntlController(this, {
            factory: () => new FileUploadElementIntl()
        });
        this._autoUpload = false;
        this._view = FileUploadView.List;
        this._multiple = false;
        this._directory = false;
        this._accept = [];
        this._strategy = null;
        this._value = [];
        this._placeholder = this._intl.intl.dropLabel;
        this._maxSize = -1;
        this._isDragging = false;
        this._fileAdded = new HTMLElementEventEmitter(this, 'fileAdded');
        this._fileRemoved = new HTMLElementEventEmitter(this, 'fileRemoved');
        this._fileFailed = new HTMLElementEventEmitter(this, 'fileFailed');
        this._filesChanged = new HTMLElementEventEmitter(this, 'filesChanged');
    }
    // #endregion
    // #region Properties
    /**
     * Returns the `{@link is}` property.
     * The `{@link is}` property represents natural name of this element.
     *
     * @public
     * @static
     * @readonly
     */
    static get is() {
        return 'mosaik-file-upload';
    }
    /**
     * Gets or sets the `autoUpload` property.
     *
     * @public
     * @attr
     */
    get autoUpload() {
        return this._autoUpload;
    }
    set autoUpload(value) {
        if (this._autoUpload !== value) {
            this._autoUpload = value;
            this.requestUpdate('autoUpload');
        }
    }
    /**
     * Gets or sets the `view` property.
     *
     * @public
     * @attr
     */
    get view() {
        return this._view;
    }
    set view(value) {
        if (this._view !== value) {
            this._view = value;
            this.requestUpdate('view');
        }
    }
    /**
     * Gets or sets the `multiple` property.
     *
     * @public
     * @attr
     */
    get multiple() {
        return this._multiple;
    }
    set multiple(value) {
        if (this._multiple !== value) {
            this._multiple = value;
            this.requestUpdate('multiple');
        }
    }
    /**
     * Gets or sets the `directory` property.
     *
     * @public
     * @attr
     */
    get directory() {
        return this._directory;
    }
    set directory(value) {
        if (this._directory !== value) {
            this._directory = value;
            this.requestUpdate('directory');
        }
    }
    /**
     * Gets or sets the `accept` property.
     *
     * @public
     */
    get accept() {
        return this._accept;
    }
    set accept(value) {
        if (this._accept !== value) {
            this._accept = value;
            this.requestUpdate('accept');
        }
    }
    /**
     * Gets or sets the `strategy` property.
     *
     * @public
     */
    get strategy() {
        return this._strategy;
    }
    set strategy(value) {
        if (this._strategy !== value) {
            this._strategy = value;
            this.requestUpdate('strategy');
        }
    }
    /**
     * Gets or sets the `value` property.
     *
     * @public
     * @override
     */
    get value() {
        return this._value;
    }
    set value(value) {
        if (this._value !== value) {
            this._value = value;
            this.requestUpdate('value');
        }
    }
    /**
     * Gets or sets the `placeholder` property.
     *
     * @public
     */
    get placeholder() {
        return this._placeholder;
    }
    set placeholder(value) {
        if (this._placeholder !== value) {
            this._placeholder = value;
            this.requestUpdate('placeholder');
        }
    }
    /**
     * Gets or sets the `maxSize` property.
     *
     * @public
     * @attr
     */
    get maxSize() {
        return this._maxSize;
    }
    set maxSize(value) {
        if (this._maxSize !== value) {
            this._maxSize = value;
            this.requestUpdate('maxSize');
        }
    }
    get isDragging() {
        return this._isDragging;
    }
    set isDragging(value) {
        if (this._isDragging !== value) {
            this._isDragging = value;
            this.requestUpdate('isDragging');
        }
    }
    get intl() {
        return this._intl.intl;
    }
    /**
     * Called when a file is added.
     * Provides reference to `{@link IEventDetail}` as event detail.
     *
     * @public
     * @readonly
     * @eventProperty
     */
    get fileAdded() {
        return this._fileAdded;
    }
    /**
     * Called when a file is deleted.
     * Provides reference to `{@link IEventDetail}` as event detail.
     *
     * @public
     * @readonly
     * @eventProperty
     */
    get fileRemoved() {
        return this._fileRemoved;
    }
    /**
     * Called when a file upload fails.
     * Provides reference to `{@link IEventDetail}` as event detail.
     *
     * @public
     * @readonly
     * @eventProperty
     */
    get fileFailed() {
        return this._fileFailed;
    }
    /**
     * Called when the files are changed.
     * Provides reference to `{@link IEventDetail}` as event detail.
     *
     * @public
     * @readonly
     * @eventProperty
     */
    get filesChanged() {
        return this._filesChanged;
    }
    // #endregion
    // #region Methods
    /**
     * @public
     */
    add(value) {
        if (!value) {
            return;
        }
        let files = new Array();
        if (value instanceof FileList) {
            files = Array.from(value);
        }
        else {
            files = Array.isArray(value) ? value : [value];
        }
        files.forEach((x) => {
            const file = IFileInfo.fromFile(x);
            const args = {
                file: file,
                cancel: false
            };
            this.onFileAdded(args);
            if (!args.cancel) {
                this._value.push(file);
                this.requestUpdate('value');
                this.onFilesChanged({ files: this._value });
                void this.upload(file);
            }
        });
    }
    /**
     * @public
     */
    delete(fileInfo) {
        const args = {
            file: fileInfo,
            cancel: false
        };
        this.onFileRemoved(args);
        if (!args.cancel) {
            this._value.splice(this._value.indexOf(fileInfo), 1);
            this.requestUpdate('value');
            this.onFilesChanged({ files: this._value });
        }
    }
    /**
     * @public
     */
    save(fileInfo) {
        return this.download(fileInfo);
    }
    /**
     * Resets the value, all kinds of validation and errors.
     *
     * @public
     */
    reset() {
        this._value = [];
        this.invalid = false;
    }
    /**
     * Checks the validity of the element and returns `true` if it is valid; otherwise, `false`.
     *
     * @public
     * @override
     */
    checkValidity() {
        return this.shadowRoot
            ? this._inputElement.checkValidity()
            : true;
    }
    /**
     * @protected
     * @template
     */
    onDataTransferred(event) {
        if (event.detail.files) {
            this.add([...event.detail.files]);
        }
    }
    /**
     * @protected
     * @override
     */
    onApplyTemplate() {
        super.onApplyTemplate();
        this._inputElement = this.getTemplatePart('input');
    }
    /**
     * @protected
     * @hidden
     */
    onPaste(event) {
        if (event.clipboardData) {
            // eslint-disable-next-line @typescript-eslint/no-for-in-array
            for (const x in event.clipboardData.items) {
                const item = event.clipboardData.items[x];
                if (item.kind === 'file') {
                    const file = item.getAsFile();
                    if (file) {
                        this.add(file);
                        event.preventDefault();
                        event.stopPropagation();
                    }
                }
            }
        }
    }
    /**
     * @private
     */
    async upload(fileInfo) {
        if (this._autoUpload && this._strategy) {
            try {
                const response = await this._strategy.upload(fileInfo);
                // Update fileInfo with the progress information
                IFileInfo.update(fileInfo, {
                    current: response.current,
                    total: response.total,
                    state: response.current === response.total ? 'done' : 'progress'
                });
            }
            catch (error) {
                IFileInfo.update(fileInfo, {
                    state: 'fail'
                });
                if (error instanceof Error) {
                    this.onFileFailed({
                        file: fileInfo,
                        error: error
                    });
                }
            }
        }
    }
    /**
     * @private
     */
    async download(fileInfo) {
        if (this._strategy) {
            try {
                const response = await this._strategy.download(fileInfo);
                Object.assign(fileInfo, {
                    current: response.current,
                    total: response.total
                });
                if (response.current === response.total && fileInfo.blob) {
                    // Assuming you have a function like "save" to handle the file download
                    save(fileInfo.blob, fileInfo.name, fileInfo.blob.type);
                }
            }
            catch (error) {
                if (error instanceof Error) {
                    this.onFileFailed({
                        file: fileInfo,
                        error: error
                    });
                }
            }
        }
    }
    /**
     * Emits the {@link fileAdded} event.
     *
     * @protected
     */
    onFileAdded(args) {
        this._fileAdded.emit(args);
    }
    /**
     * Emits the {@link fileRemoved} event.
     *
     * @protected
     */
    onFileRemoved(args) {
        this._fileRemoved.emit(args);
    }
    /**
     * Emits the {@link fileFailed} event.
     *
     * @protected
     */
    onFileFailed(args) {
        this._fileFailed.emit(args);
    }
    /**
     * Emits the {@link filesChanged} event.
     *
     * @protected
     */
    onFilesChanged(args) {
        this._filesChanged.emit(args);
    }
};
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], FileUploadElement.prototype, "autoUpload", null);
__decorate([
    Attribute({ type: String }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], FileUploadElement.prototype, "view", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], FileUploadElement.prototype, "multiple", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], FileUploadElement.prototype, "directory", null);
__decorate([
    Property({ type: (Array) }),
    __metadata("design:type", Array),
    __metadata("design:paramtypes", [Array])
], FileUploadElement.prototype, "accept", null);
__decorate([
    Property({ type: Object }),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [Object])
], FileUploadElement.prototype, "strategy", null);
__decorate([
    Property({ type: (Array) }),
    __metadata("design:type", Array),
    __metadata("design:paramtypes", [Array])
], FileUploadElement.prototype, "value", null);
__decorate([
    Property({ type: String }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], FileUploadElement.prototype, "placeholder", null);
__decorate([
    Attribute({ type: Number }),
    __metadata("design:type", Number),
    __metadata("design:paramtypes", [Number])
], FileUploadElement.prototype, "maxSize", null);
__decorate([
    Property({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], FileUploadElement.prototype, "isDragging", null);
__decorate([
    Emit({ eventName: 'fileAdded' }),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [])
], FileUploadElement.prototype, "fileAdded", null);
__decorate([
    Emit({ eventName: 'fileRemoved' }),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [])
], FileUploadElement.prototype, "fileRemoved", null);
__decorate([
    Emit({ eventName: 'fileFailed' }),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [])
], FileUploadElement.prototype, "fileFailed", null);
__decorate([
    Emit({ eventName: 'filesChanged' }),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [])
], FileUploadElement.prototype, "filesChanged", null);
__decorate([
    Listen('paste'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [ClipboardEvent]),
    __metadata("design:returntype", void 0)
], FileUploadElement.prototype, "onPaste", null);
FileUploadElement = __decorate([
    Component({
        selector: 'mosaik-file-upload',
        template: fileUploadElementTemplate,
        themes: {
            joy: fileUploadElementJoyStyle,
            memphis: fileUploadElementMemphisStyle,
            cosmopolitan: fileUploadElementCosmopolitanStyle
        },
        imports: [
            FilePickerElement,
            FileUploadItemElement,
            ButtonElement,
            DropZoneElement,
            ListElement,
            TableElement,
            ChipElement,
            CardElement
        ]
    }),
    __metadata("design:paramtypes", [])
], FileUploadElement);
export { FileUploadElement };
function save(data, name, mime) {
    const blob = new Blob([data], { type: mime });
    const a = RendererServiceLocator.current.createElement('a');
    const url = URL.createObjectURL(blob);
    a.href = url;
    a.download = name;
    RendererServiceLocator.current.appendChild(document.body, a);
    a.click();
    setTimeout(() => {
        RendererServiceLocator.current.removeChild(document.body, a);
        URL.revokeObjectURL(url);
    }, 0);
}
//# sourceMappingURL=FileUploadElement.js.map