// #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 { RendererServiceLocator } from '../../../../Dom/Renderer';
import { Emit } from '../../../../Events/Decorators/EmitDecorator';
import { Listen } from '../../../../Events/Decorators/ListenDecorator';
import { HTMLElementEventEmitter } from '@breadstone/mosaik-elements';
import { IntlController } from '../../../../Intl/IntlController';
import { Appearanceable } from '../../../Behaviors/Appearanceable';
import { Disableable } from '../../../Behaviors/Disableable';
import { Invalidable } from '../../../Behaviors/Invalidable';
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 { fileUploadElementJoyStyle } from './Themes/FileUploadElement.Joy';
import { fileUploadElementRetroStyle } from './Themes/FileUploadElement.Retro';
import { fileUploadElementCosmopolitanStyle } from './Themes/FileUploadElement.Cosmopolitan';
import { Themeable } from '../../../Behaviors/Themeable';
// #endregion
/**
 * The `{@link FileUploadElement}` element.
 *
 * @fires fileUploadAdded - Fired when a file is added.
 * @fires fileUploadDeleted - Fired when a file is deleted.
 * @fires fileUploadFailed - Fired when a file upload fails.
 * @fires fileUploadChanged - Fired when the files are changed.
 *
 * @public
 */
let FileUploadElement = class FileUploadElement extends Themeable(Disableable(Appearanceable(Variantable(Invalidable(Valueable(CustomElement)))))) {
    // #region Fields
    _fileAdded;
    _fileDeleted;
    _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._fileDeleted = new HTMLElementEventEmitter(this, 'fileDeleted');
        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 fileUploadAdded() {
        return this._fileAdded;
    }
    /**
     * Called when a file is deleted.
     * Provides reference to `{@link IEventDetail}` as event detail.
     *
     * @public
     * @readonly
     * @eventProperty
     */
    get fileUploadDeleted() {
        return this._fileDeleted;
    }
    /**
     * Called when a file upload fails.
     * Provides reference to `{@link IEventDetail}` as event detail.
     *
     * @public
     * @readonly
     * @eventProperty
     */
    get fileUploadFailed() {
        return this._fileFailed;
    }
    /**
     * Called when the files are changed.
     * Provides reference to `{@link IEventDetail}` as event detail.
     *
     * @public
     * @readonly
     * @eventProperty
     */
    get fileUploadChanged() {
        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.onFileDeleted(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) {
        this.add(event.detail.data.files);
    }
    /**
     * @protected
     * @override
     */
    onApplyTemplate() {
        super.onApplyTemplate();
        this._inputElement = this.getTemplatePart('input');
    }
    /**
     * @protected
     * @hidden
     */
    onPaste(event) {
        if (event.clipboardData) {
            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 fileUploadAdded} event.
     *
     * @protected
     */
    onFileAdded(args) {
        this._fileAdded.emit(args);
    }
    /**
     * Emits the {@link fileUploadDeleted} event.
     *
     * @protected
     */
    onFileDeleted(args) {
        this._fileDeleted.emit(args);
    }
    /**
     * Emits the {@link fileUploadFailed} event.
     *
     * @protected
     */
    onFileFailed(args) {
        this._fileFailed.emit(args);
    }
    /**
     * Emits the {@link fileUploadChanged} 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 }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], FileUploadElement.prototype, "isDragging", null);
__decorate([
    Emit({ eventName: 'fileUploadAdded' }),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [])
], FileUploadElement.prototype, "fileUploadAdded", null);
__decorate([
    Emit({ eventName: 'fileUploadDeleted' }),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [])
], FileUploadElement.prototype, "fileUploadDeleted", null);
__decorate([
    Emit({ eventName: 'fileUploadFailed' }),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [])
], FileUploadElement.prototype, "fileUploadFailed", null);
__decorate([
    Emit({ eventName: 'fileUploadChanged' }),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [])
], FileUploadElement.prototype, "fileUploadChanged", 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,
            retro: fileUploadElementRetroStyle,
            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