var _a, _b;
import { __decorate, __extends } from "tslib";
import Component from 'vue-class-component';
import { Prop, Watch } from 'vue-property-decorator';
import { MBadgeDirective, MBadgeState } from '../../directives/badge/badge';
import { BADGE_NAME, FILE_DROP_NAME } from '../../directives/directive-names';
import { MFileDropDirective } from '../../directives/file-drop/file-drop';
import { fileSize } from '../../filters/filesize/filesize';
import { FILESIZE_NAME } from '../../filters/filter-names';
import { MediaQueries } from '../../mixins/media-queries/media-queries';
import FilePlugin, { DEFAULT_STORE_NAME, MFileRejectionCause, MFileStatus } from '../../utils/file/file';
import MediaQueriesPlugin from '../../utils/media-queries/media-queries';
import UserAgentUtil from '../../utils/user-agent/user-agent';
import { ModulVue } from '../../utils/vue/vue';
import { MButton } from '../button/button';
import { FILE_UPLOAD_NAME } from '../component-names';
import { MFileSelect } from '../file-select/file-select';
import { MIconButton } from '../icon-button/icon-button';
import { MIconFile } from '../icon-file/icon-file';
import { MLink } from '../link/link';
import { MMessage } from '../message/message';
import { MModal } from '../modal/modal';
import { MProgress, MProgressState } from '../progress/progress';
import WithRender from './file-upload.html?style=./file-upload.scss';
var COMPLETED_FILES_VISUAL_HINT_DELAY = 1000;
var defaultDragEvent = function (e) {
    e.preventDefault();
    e.stopPropagation();
    e.dataTransfer.dropEffect = 'none';
};
var MFileUpload = /** @class */ (function (_super) {
    __extends(MFileUpload, _super);
    function MFileUpload() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.tooltipCancel = _this.$i18n.translate('m-file-upload:cancelFileUpload');
        _this.tooltipDelete = _this.$i18n.translate('m-file-upload:deleteUploadedFile');
        _this.internalOpen = false;
        return _this;
    }
    Object.defineProperty(MFileUpload.prototype, "isDropZoneEnabled", {
        get: function () {
            return UserAgentUtil.isDesktop() && this.$mq.state.isMqMinS;
        },
        enumerable: false,
        configurable: true
    });
    MFileUpload.prototype.created = function () {
        this.updateValidationOptions();
    };
    MFileUpload.prototype.destroyed = function () {
        this.$file.destroy(this.storeName);
    };
    MFileUpload.prototype.updateValidationOptions = function () {
        this.$file.setValidationOptions({
            allowedExtensions: this.allowedExtensions,
            rejectedExtensions: this.rejectedExtensions,
            maxSizeKb: this.maxSizeKb,
            maxFiles: this.propMaxFiles,
            customValidationFunction: this.customValidation ? this.customValidation.validationFunction : undefined
        }, this.storeName);
    };
    MFileUpload.prototype.openChanged = function (open) {
        this.internalOpen = open;
    };
    MFileUpload.prototype.onFilesChanged = function () {
        var newReadyFiles = [];
        for (var _i = 0, _a = this.readyFiles; _i < _a.length; _i++) {
            var f = _a[_i];
            if (!f.hasOwnProperty('completeHinted')) {
                this.$set(f, 'completeHinted', false);
                newReadyFiles.push(f);
            }
        }
        if (newReadyFiles.length > 0) {
            this.$emit('files-ready', this.readyFiles);
        }
    };
    MFileUpload.prototype.onFreshlyCompletedFilesChanged = function () {
        var _this = this;
        if (this.freshlyCompletedFiles.length > 0) {
            setTimeout(function () {
                for (var _i = 0, _a = _this.freshlyCompletedFiles; _i < _a.length; _i++) {
                    var f = _a[_i];
                    f.completeHinted = true;
                }
            }, COMPLETED_FILES_VISUAL_HINT_DELAY);
        }
    };
    MFileUpload.prototype.onFilesRejected = function () {
        var nbNewRejection = this.rejectedFiles.reduce(function (cnt, f) {
            var nbNewRejection = 0;
            if (!f.isOldRejection) {
                ++nbNewRejection;
                f.isOldRejection = true;
            }
            return cnt + nbNewRejection;
        }, 0);
        if (nbNewRejection > 0) {
            if (this.$refs.modal && this.$refs.modal.$refs) {
                this.$refs.modal.$refs.body.scrollTop = 0;
            }
            // TODO Change function to have a smooth scroll when it will work on a diferent element than the body of the page
            // ScrollTo.startScroll(bodyRef, 0, ScrollToDuration.Regular);
        }
    };
    MFileUpload.prototype.onPortalAfterOpen = function () {
        var _this = this;
        this.dropEvents.forEach(function (evt) {
            _this.$refs.modal.$refs.modalWrap.addEventListener(evt, defaultDragEvent);
        });
    };
    MFileUpload.prototype.onMessageClose = function () {
        for (var _i = 0, _a = this.rejectedFiles; _i < _a.length; _i++) {
            var f = _a[_i];
            this.$file.remove(f.uid, this.storeName);
        }
    };
    MFileUpload.prototype.onAddClick = function () {
        this.$emit('done', this.completedFiles);
        this.$refs.modal.closeModal();
    };
    MFileUpload.prototype.onCancelClick = function () {
        this.$emit('cancel');
        this.$refs.modal.closeModal();
    };
    MFileUpload.prototype.onUploadCancel = function (file) {
        file.status === MFileStatus.UPLOADING
            ? this.$emit('file-upload-cancel', file)
            : this.onFileRemove(file);
    };
    MFileUpload.prototype.onFileRemove = function (file) {
        this.$emit('file-remove', file);
        this.$file.remove(file.uid, this.storeName);
    };
    MFileUpload.prototype.onOpen = function () {
        this.$emit('open');
        this.propOpen = true;
        this.updateValidationOptions();
    };
    MFileUpload.prototype.onClose = function () {
        var _this = this;
        this.propOpen = false;
        this.$emit('close');
        this.allFiles
            .filter(function (f) { return f.status === MFileStatus.UPLOADING; })
            .forEach(this.onUploadCancel);
        this.$file.clear(this.storeName);
        this.dropEvents.forEach(function (evt) {
            _this.$refs.modal.$refs.modalWrap.removeEventListener(evt, defaultDragEvent);
        });
    };
    MFileUpload.prototype.getFileStatus = function (file) {
        switch (file.status) {
            case MFileStatus.FAILED:
                return MProgressState.Error;
            case MFileStatus.COMPLETED:
                return MProgressState.Completed;
            default:
                return MProgressState.InProgress;
        }
    };
    MFileUpload.prototype.getBadgeState = function (file) {
        switch (file.status) {
            case MFileStatus.FAILED:
                return MBadgeState.Error;
            case MFileStatus.COMPLETED:
                return MBadgeState.Completed;
            default:
                return undefined;
        }
    };
    MFileUpload.prototype.hasExtensionsRejection = function (file) {
        return file.rejection === MFileRejectionCause.FILE_TYPE;
    };
    MFileUpload.prototype.hasSizeRejection = function (file) {
        return file.rejection === MFileRejectionCause.FILE_SIZE;
    };
    MFileUpload.prototype.hasMaxFilesRejection = function (file) {
        return file.rejection === MFileRejectionCause.MAX_FILES;
    };
    MFileUpload.prototype.hasCustomValidationRejection = function (file) {
        return file.rejection === MFileRejectionCause.CUSTOM_VALIDATION;
    };
    Object.defineProperty(MFileUpload.prototype, "title", {
        get: function () {
            return this.fileReplacement ? this.$i18n.translate('m-file-upload:header-title-file-replacement') : this.$i18n.translate('m-file-upload:header-title', {}, this.propMaxFiles);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MFileUpload.prototype, "buttonAdd", {
        get: function () {
            return this.fileReplacement ? this.$i18n.translate('m-file-upload:replace') : this.$i18n.translate('m-file-upload:add');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MFileUpload.prototype, "fileAllowedExtensions", {
        get: function () {
            return this.allowedExtensions.join(', ');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MFileUpload.prototype, "isAddBtnEnabled", {
        get: function () {
            return (this.completedFiles.length > 0 && this.uploadingFilesOnly.length === 0);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MFileUpload.prototype, "readyFiles", {
        get: function () {
            return this.allFiles.filter(function (f) { return f.status === MFileStatus.READY; });
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MFileUpload.prototype, "freshlyCompletedFiles", {
        get: function () {
            return this.allFiles.filter(function (f) { return f.status === MFileStatus.COMPLETED && !f.completeHinted; });
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MFileUpload.prototype, "uploadingFilesOnly", {
        get: function () {
            return this.allFiles.filter(function (f) {
                return f.status === MFileStatus.UPLOADING ||
                    (f.status === MFileStatus.COMPLETED && !f.completeHinted);
            });
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MFileUpload.prototype, "uploadingFiles", {
        get: function () {
            return this.allFiles.filter(function (f) {
                return f.status === MFileStatus.UPLOADING ||
                    f.status === MFileStatus.FAILED ||
                    (f.status === MFileStatus.COMPLETED && !f.completeHinted);
            });
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MFileUpload.prototype, "completedFiles", {
        get: function () {
            return this.allFiles.filter(function (f) { return f.status === MFileStatus.COMPLETED && f.completeHinted; });
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MFileUpload.prototype, "rejectedFiles", {
        get: function () {
            return this.allFiles.filter(function (f) { return f.status === MFileStatus.REJECTED; });
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MFileUpload.prototype, "allFiles", {
        get: function () {
            return this.$file.files(this.storeName);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MFileUpload.prototype, "hasUploadingFiles", {
        get: function () {
            return this.uploadingFiles.length === 0;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MFileUpload.prototype, "hasCompletedFiles", {
        get: function () {
            return this.completedFiles.length === 0;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MFileUpload.prototype, "buttonCompletedStyle", {
        get: function () {
            return !this.hasCompletedFiles ? 'display: flex;' : undefined;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MFileUpload.prototype, "hasRejectedFiles", {
        get: function () {
            return this.rejectedFiles.length !== 0;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MFileUpload.prototype, "hasAllowedExtensions", {
        get: function () {
            return this.allowedExtensions.length > 0;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MFileUpload.prototype, "propOpen", {
        get: function () {
            return this.open ? this.open : this.internalOpen;
        },
        set: function (value) {
            if (value !== this.internalOpen) {
                this.internalOpen = value;
                this.$emit('update:open', value);
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MFileUpload.prototype, "propMaxFiles", {
        get: function () {
            return this.fileReplacement ? 1 : this.maxFiles;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MFileUpload.prototype, "multipleSelection", {
        get: function () {
            return this.propMaxFiles !== undefined && this.propMaxFiles > 1;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MFileUpload.prototype, "dropEvents", {
        get: function () {
            return ['drag', 'dragstart', 'dragend', 'dragover', 'dragenter', 'dragleave', 'drop'];
        },
        enumerable: false,
        configurable: true
    });
    __decorate([
        Prop({ default: function () { return []; } })
    ], MFileUpload.prototype, "allowedExtensions", void 0);
    __decorate([
        Prop({ default: function () { return []; } })
    ], MFileUpload.prototype, "rejectedExtensions", void 0);
    __decorate([
        Prop()
    ], MFileUpload.prototype, "maxSizeKb", void 0);
    __decorate([
        Prop()
    ], MFileUpload.prototype, "maxFiles", void 0);
    __decorate([
        Prop()
    ], MFileUpload.prototype, "selectionHelpMessage", void 0);
    __decorate([
        Prop({
            default: DEFAULT_STORE_NAME
        })
    ], MFileUpload.prototype, "storeName", void 0);
    __decorate([
        Prop()
    ], MFileUpload.prototype, "open", void 0);
    __decorate([
        Prop({ default: false })
    ], MFileUpload.prototype, "fileReplacement", void 0);
    __decorate([
        Prop()
    ], MFileUpload.prototype, "customValidation", void 0);
    __decorate([
        Watch('allowedExtensions'),
        Watch('rejectedExtensions'),
        Watch('maxSizeKb'),
        Watch('maxFiles'),
        Watch('customValidation')
    ], MFileUpload.prototype, "updateValidationOptions", null);
    __decorate([
        Watch('open')
    ], MFileUpload.prototype, "openChanged", null);
    __decorate([
        Watch('readyFiles')
    ], MFileUpload.prototype, "onFilesChanged", null);
    __decorate([
        Watch('freshlyCompletedFiles')
    ], MFileUpload.prototype, "onFreshlyCompletedFilesChanged", null);
    __decorate([
        Watch('rejectedFiles')
    ], MFileUpload.prototype, "onFilesRejected", null);
    MFileUpload = __decorate([
        WithRender,
        Component({
            components: {
                MButton: MButton,
                MModal: MModal,
                MMessage: MMessage,
                MFileSelect: MFileSelect,
                MIconFile: MIconFile,
                MIconButton: MIconButton,
                MProgress: MProgress,
                MLink: MLink
            },
            directives: (_a = {},
                _a[FILE_DROP_NAME] = MFileDropDirective,
                _a[BADGE_NAME] = MBadgeDirective,
                _a),
            filters: (_b = {},
                _b[FILESIZE_NAME] = fileSize,
                _b),
            mixins: [
                MediaQueries
            ]
        })
    ], MFileUpload);
    return MFileUpload;
}(ModulVue));
export { MFileUpload };
var FileUploadPlugin = {
    install: function (v, options) {
        v.use(FilePlugin);
        v.use(MediaQueriesPlugin);
        v.component(FILE_UPLOAD_NAME, MFileUpload);
    }
};
export default FileUploadPlugin;
//# sourceMappingURL=file-upload.js.map