"use strict";
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);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FlowUploader = exports.FlowHelper = exports.FileFlow = exports.ExistenceAction = void 0;
var picture_helper_1 = require("./../../ui/files/picture-helper");
var constants_1 = require("../../constants/constants");
var aurelia_framework_1 = require("aurelia-framework");
var aurelia_event_aggregator_1 = require("aurelia-event-aggregator");
var box_1 = require("../../modules/box");
var aurelia_framework_2 = require("aurelia-framework");
var aurelia_i18n_1 = require("aurelia-i18n");
var custom_logger_1 = require("../../modules/custom-logger");
var compressorjs_1 = __importDefault(require("compressorjs"));
var auth_service_1 = require("../../security/auth-service");
var heic2any_1 = __importDefault(require("./utilities/heic2any"));
var file_storage_service_1 = require("./../../services/file-storage-service");
var fileTypes = /(\.|\/)(msg|eml|gif|jpe?g|png|docx?|dotx?|xlsx?|xlsm?|pptx?|pdf|zip|x-zip-compressed|msword|ms-excel|ms-powerpoint|vnd.openxmlformats-officedocument.wordprocessingml.document|vnd.openxmlformats-officedocument.spreadsheetml.sheet|vnd.openxmlformats-officedocument.presentationml.presentation|vnd.ms-excel.sheet.macroEnabled.12)$/i, fileSize = 104857600;
var ExistenceAction;
(function (ExistenceAction) {
    ExistenceAction[ExistenceAction["None"] = 0] = "None";
    ExistenceAction[ExistenceAction["Replace"] = 1] = "Replace";
    ExistenceAction[ExistenceAction["Duplicate"] = 2] = "Duplicate";
    ExistenceAction[ExistenceAction["Cancel"] = 3] = "Cancel";
})(ExistenceAction = exports.ExistenceAction || (exports.ExistenceAction = {}));
;
var FileFlow = exports.FileFlow = (function () {
    function FileFlow(fileFlow, ea) {
        var _this = this;
        this.ea = ea;
        this.name = "";
        this.displayName = "";
        this.size = 0;
        this.averageSpeed = 0;
        this.speed = 0;
        this.isPaused = false;
        this.isReuploaded = false;
        this.isCanceled = false;
        this.progress = 0;
        this.isComplete = false;
        this.errorMessage = "";
        this.isError = false;
        this.serverId = 0;
        this.uid = fileFlow.uniqueIdentifier;
        this.name = fileFlow.name;
        this.size = fileFlow.size;
        this.flow = fileFlow.flowObj;
        this.fileFlow = fileFlow;
        var reader = new FileReader();
        reader.readAsDataURL(this.fileFlow.file);
        reader.onloadend = function () {
            _this.previewSrc = reader.result;
        };
    }
    Object.defineProperty(FileFlow.prototype, "isUploading", {
        get: function () {
            return !this.isError && !this.isPaused && !this.isComplete;
        },
        enumerable: false,
        configurable: true
    });
    FileFlow.prototype.pause = function () {
        this.fileFlow.pause();
        this.isPaused = true;
    };
    FileFlow.prototype.resume = function () {
        this.fileFlow.resume();
        this.isPaused = true;
    };
    FileFlow.prototype.cancel = function () {
        this.isPaused = true;
        this.isCanceled = true;
        this.fileFlow.cancel();
    };
    FileFlow.prototype.retry = function () {
        this.isError = false;
        this.isComplete = false;
        this.fileFlow.bootstrap();
        this.fileFlow.resume();
    };
    __decorate([
        aurelia_framework_1.observable,
        __metadata("design:type", Object)
    ], FileFlow.prototype, "progress", void 0);
    __decorate([
        aurelia_framework_1.observable,
        __metadata("design:type", Object)
    ], FileFlow.prototype, "isComplete", void 0);
    __decorate([
        aurelia_framework_1.observable,
        __metadata("design:type", Object)
    ], FileFlow.prototype, "errorMessage", void 0);
    __decorate([
        aurelia_framework_1.observable,
        __metadata("design:type", Object)
    ], FileFlow.prototype, "isError", void 0);
    __decorate([
        aurelia_framework_1.observable,
        __metadata("design:type", Boolean),
        __metadata("design:paramtypes", [])
    ], FileFlow.prototype, "isUploading", null);
    __decorate([
        aurelia_framework_1.observable,
        __metadata("design:type", Object)
    ], FileFlow.prototype, "previewSrc", void 0);
    return FileFlow;
}());
var FlowHelper = exports.FlowHelper = (function () {
    function FlowHelper(logger, target, eventAggregator, allowDuplicateUploads, confirmUploadFn, acceptedExtensions, resizePicture, folderName, accessToken, compressorOptions, autoConvert, useUniqueName, pictureQuality) {
        if (confirmUploadFn === void 0) { confirmUploadFn = null; }
        if (acceptedExtensions === void 0) { acceptedExtensions = null; }
        if (resizePicture === void 0) { resizePicture = false; }
        if (folderName === void 0) { folderName = ""; }
        if (accessToken === void 0) { accessToken = null; }
        if (autoConvert === void 0) { autoConvert = false; }
        if (useUniqueName === void 0) { useUniqueName = false; }
        if (pictureQuality === void 0) { pictureQuality = 0.7; }
        var _this = this;
        this.logger = logger;
        this.eventAggregator = eventAggregator;
        this.acceptedExtensions = acceptedExtensions;
        this.compressorOptions = compressorOptions;
        this.isUploading = false;
        this.progress = 0;
        this.innerUploadingFiles = [];
        this.resizePicture = false;
        this.autoConvert = false;
        this.folderName = folderName;
        this.useUniqueName = useUniqueName;
        this.resizePicture = resizePicture;
        this.autoConvert = autoConvert;
        this.pictureQuality = pictureQuality;
        this.params = {
            target: target,
            allowDuplicateUploads: allowDuplicateUploads,
            chunkSize: 1024 * 1024,
            query: {
                "folderName": this.folderName
            },
            generateUniqueIdentifier: function () { return Math.random().toString(36).substr(2, 9); }
        };
        if (accessToken != null) {
            this.params.headers = {
                "Authorization": "Bearer ".concat(accessToken)
            };
        }
        this.i18n = aurelia_framework_2.Container.instance.get(aurelia_i18n_1.I18N);
        this.setFileTypes(acceptedExtensions);
        this.flow = new Flow(this.params);
        this.flow.on("uploadStart", function () {
            _this.isUploading = true;
        });
        this.flow.on('filesSubmitted', function (array, event) { return __awaiter(_this, void 0, void 0, function () {
            var startUploading, confirm_1;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (array.length == 0)
                            return [2, false];
                        if (array.length > 1 && allowDuplicateUploads == false) {
                            this.logger.LogError(this.i18n.tr('fileUpload.onlyOneDocument', { ns: 'common' }), null, null, true);
                            return [2, false];
                        }
                        startUploading = function () { return __awaiter(_this, void 0, void 0, function () {
                            var _this = this;
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0:
                                        this.showLoader(true);
                                        return [4, this.checkArray(array)];
                                    case 1:
                                        _a.sent();
                                        if (!this.autoConvert) return [3, 3];
                                        return [4, this.convertHeicToJpeg(array)];
                                    case 2:
                                        _a.sent();
                                        _a.label = 3;
                                    case 3:
                                        if (!this.resizePicture) return [3, 5];
                                        return [4, this.processArray(array)];
                                    case 4:
                                        _a.sent();
                                        _a.label = 5;
                                    case 5:
                                        this.flow.opts.query["folderName"] = this.folderName;
                                        return [4, Promise.all(array.map(function (val) { return __awaiter(_this, void 0, void 0, function () {
                                                var fileFlow;
                                                return __generator(this, function (_a) {
                                                    switch (_a.label) {
                                                        case 0:
                                                            fileFlow = new FileFlow(val, this.eventAggregator);
                                                            fileFlow.isReuploaded = val.isReuploaded;
                                                            return [4, this.fileAdded(fileFlow)];
                                                        case 1:
                                                            _a.sent();
                                                            this.innerUploadingFiles.push(fileFlow);
                                                            return [2];
                                                    }
                                                });
                                            }); }))];
                                    case 6:
                                        _a.sent();
                                        this.flow.upload();
                                        return [2];
                                }
                            });
                        }); };
                        if (!(confirmUploadFn != null)) return [3, 2];
                        return [4, confirmUploadFn({ array: array, event: event })];
                    case 1:
                        confirm_1 = _a.sent();
                        if (confirm_1 == true) {
                            startUploading();
                        }
                        else {
                            this.flow.cancel();
                            console.log("upload cancelled by user");
                        }
                        return [3, 3];
                    case 2:
                        startUploading();
                        _a.label = 3;
                    case 3: return [2];
                }
            });
        }); });
        this.flow.on('fileAdded', function (file, event) { return __awaiter(_this, void 0, void 0, function () {
            var filename, extension, uploadErrors;
            return __generator(this, function (_a) {
                filename = picture_helper_1.PictureHelper.getFileNameWithoutExtension(file.name);
                if (this.useUniqueName) {
                    filename += "_" + new Date().getTime().toString();
                }
                extension = picture_helper_1.PictureHelper.getFileExtension(file.name);
                file.displayName = file.name;
                file.name = filename + extension;
                uploadErrors = [];
                if (!this.fileTypes.test(extension))
                    uploadErrors.push(this.i18n.tr('fileUpload.invalidFileType', { ns: 'common' }));
                if (file.size > fileSize)
                    uploadErrors.push(this.i18n.tr('fileUpload.invalidFileSize', { ns: 'common' }));
                if (uploadErrors.length > 0) {
                    this.logger.LogError(uploadErrors.join("</br>"), null, null, true);
                    return [2, false];
                }
                return [2];
            });
        }); });
        this.flow.on('fileSuccess', function (file, message) {
            var fileUploaded = _this.innerUploadingFiles.find(function (f) { return f.uid === file.uniqueIdentifier; });
            if (message != null && message.length > 0) {
                var jsonMessage = JSON.parse(message);
                if (jsonMessage.ServerId)
                    fileUploaded.serverId = jsonMessage.ServerId;
                if (jsonMessage.Thumbnail)
                    fileUploaded.thumbnail = jsonMessage.Thumbnail;
                if (jsonMessage.Log)
                    fileUploaded.log = jsonMessage.Log;
                if (jsonMessage.Url)
                    fileUploaded.url = jsonMessage.Url;
            }
            fileUploaded.displayName = file.displayName;
            _this.fileUploaded(fileUploaded);
            fileUploaded.isComplete = true;
            _this.showLoader(false);
        });
        this.flow.on('fileError', function (file, message) {
            _this.showLoader(false);
            var errorFile = _this.innerUploadingFiles.find(function (f) { return f.uid === file.uniqueIdentifier; });
            if (errorFile != null) {
                errorFile.isError = true;
                errorFile.progress = 0;
                if ((message === null || message === void 0 ? void 0 : message.length) > 0) {
                    var parseErrorMessage = JSON.parse(message);
                    errorFile.errorMessage = parseErrorMessage.Message;
                }
            }
            _this.isUploading = false;
        });
        this.flow.on('complete', function () {
            _this.showLoader(false);
            if (_this.uploadComplete != null)
                _this.uploadComplete(_this.innerUploadingFiles);
        });
        this.flow.on('fileProgress', function (file, chunk) {
            var uploadingFile = _this.innerUploadingFiles.find(function (f) { return f.uid === file.uniqueIdentifier; });
            var progress = file.progress() * 100;
            if (uploadingFile)
                uploadingFile.progress = progress;
        });
    }
    FlowHelper.prototype.processArray = function (array) {
        return __awaiter(this, void 0, void 0, function () {
            var promises, results;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        promises = array.map(this.resizeImage, this);
                        return [4, Promise.all(promises)];
                    case 1:
                        results = _a.sent();
                        results.forEach(function (result) {
                            if (result != null) {
                                _this.createAndReplaceNewFileFlow(result[0], result[1], array, true);
                            }
                        });
                        return [2];
                }
            });
        });
    };
    FlowHelper.prototype.convertHeicToJpeg = function (array) {
        return __awaiter(this, void 0, void 0, function () {
            var toReplace, array_1, array_1_1, file, extension, filename, newFile, e_1_1;
            var e_1, _a;
            var _this = this;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        toReplace = new Map();
                        _b.label = 1;
                    case 1:
                        _b.trys.push([1, 6, 7, 8]);
                        array_1 = __values(array), array_1_1 = array_1.next();
                        _b.label = 2;
                    case 2:
                        if (!!array_1_1.done) return [3, 5];
                        file = array_1_1.value;
                        extension = file.name.substr(file.name.lastIndexOf('.')).toLowerCase();
                        if (!(extension == ".heic" || extension == ".heif")) return [3, 4];
                        filename = file.name.replace(/\.[^/.]+$/, "");
                        file.name = filename + ".jpeg";
                        return [4, (0, heic2any_1.default)({
                                blob: file.file,
                                toType: "image/jpeg",
                                quality: 1.0
                            })];
                    case 3:
                        newFile = (_b.sent());
                        toReplace.set(file, newFile);
                        _b.label = 4;
                    case 4:
                        array_1_1 = array_1.next();
                        return [3, 2];
                    case 5: return [3, 8];
                    case 6:
                        e_1_1 = _b.sent();
                        e_1 = { error: e_1_1 };
                        return [3, 8];
                    case 7:
                        try {
                            if (array_1_1 && !array_1_1.done && (_a = array_1.return)) _a.call(array_1);
                        }
                        finally { if (e_1) throw e_1.error; }
                        return [7];
                    case 8:
                        toReplace.forEach(function (resizedFile, originalFileFlow) {
                            _this.createAndReplaceNewFileFlow(originalFileFlow, resizedFile, array, false);
                        });
                        return [2];
                }
            });
        });
    };
    FlowHelper.prototype.checkArray = function (array) {
        return __awaiter(this, void 0, void 0, function () {
            var promises, results;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        promises = array.map(function (f) { return _this.askToKeep(f); });
                        return [4, Promise.all(promises)];
                    case 1:
                        results = _a.sent();
                        results.forEach(function (result) {
                            result.file.isReuploaded = result.toKeep == ExistenceAction.Replace;
                            if (result.toKeep == ExistenceAction.Cancel) {
                                _this.flow.removeFile(result.file);
                                array.remove(result.file);
                            }
                            else if (result.toKeep == ExistenceAction.Duplicate) {
                                result.file.name = picture_helper_1.PictureHelper.getFileNameWithoutExtension(result.file.name) + "_" + new Date().getTime().toString() + picture_helper_1.PictureHelper.getFileExtension(result.file.name);
                            }
                        });
                        return [2];
                }
            });
        });
    };
    FlowHelper.prototype.createAndReplaceNewFileFlow = function (originalFileFlow, resizedFile, array, resize) {
        var uniqueIdentifier = originalFileFlow.uniqueIdentifier;
        var toRemoveIndex = this.flow.files.findIndex(function (f) { return f.uniqueIdentifier == uniqueIdentifier; });
        this.flow.files.splice(toRemoveIndex, 1);
        var ff = new Flow.FlowFile(this.flow, resizedFile, uniqueIdentifier);
        ff.name = originalFileFlow.name;
        this.flow.files.push(ff);
        var originalIndex = array.findIndex(function (original) { return original.uniqueIdentifier == ff.uniqueIdentifier; });
        array[originalIndex] = ff;
        if (resize) {
            ff.resized = true;
        }
    };
    FlowHelper.prototype.resizeImage = function (flowFile) {
        var _this = this;
        if (flowFile && flowFile.resized)
            return Promise.resolve(null);
        return new Promise(function (resolve, reject) {
            var options = {
                quality: _this.pictureQuality,
                maxWidth: 1000,
                success: function (result) {
                    resolve([flowFile, result]);
                },
                error: function (err) {
                    console.log(err.message);
                    reject();
                }
            };
            Object.assign(options, _this.compressorOptions);
            new compressorjs_1.default(flowFile.file, options);
        });
    };
    FlowHelper.prototype.askToKeep = function (file) {
        return __awaiter(this, void 0, void 0, function () {
            var toKeep;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.checkExistence(file)];
                    case 1:
                        toKeep = _a.sent();
                        return [2, { file: file, toKeep: toKeep }];
                }
            });
        });
    };
    FlowHelper.prototype.setFileTypes = function (acceptedExtensions) {
        if (acceptedExtensions != null && acceptedExtensions.length > 0) {
            var cleanDots = acceptedExtensions.replace(/\./g, '').replace(/\,/g, "|");
            this.fileTypes = new RegExp('(\.|\/)' + cleanDots + '$', 'i');
        }
        else {
            this.fileTypes = fileTypes;
        }
    };
    FlowHelper.prototype.resetFiles = function () {
        this.innerUploadingFiles = [];
    };
    Object.defineProperty(FlowHelper.prototype, "uploadingFiles", {
        get: function () {
            return this.innerUploadingFiles.filter(function (f) { return !f.isCanceled && !f.isComplete; });
        },
        enumerable: false,
        configurable: true
    });
    FlowHelper.prototype.assignBrowse = function (element, attributes) {
        this.flow.assignBrowse([element], false, false, attributes);
    };
    FlowHelper.prototype.assignDrop = function (element) {
        this.flow.assignDrop([element]);
    };
    FlowHelper.prototype.pauseAll = function () {
        this.uploadingFiles.forEach(function (f) { return f.pause(); });
    };
    FlowHelper.prototype.cancelAll = function () {
        this.uploadingFiles.forEach(function (f) { return f.cancel(); });
    };
    FlowHelper.prototype.resumeAll = function () {
        this.uploadingFiles.forEach(function (f) { return f.resume(); });
    };
    __decorate([
        aurelia_framework_1.observable,
        __metadata("design:type", Boolean)
    ], FlowHelper.prototype, "isUploading", void 0);
    __decorate([
        aurelia_framework_1.observable,
        __metadata("design:type", Number)
    ], FlowHelper.prototype, "progress", void 0);
    __decorate([
        aurelia_framework_1.observable,
        __metadata("design:type", Array)
    ], FlowHelper.prototype, "innerUploadingFiles", void 0);
    __decorate([
        aurelia_framework_1.observable,
        __metadata("design:type", String)
    ], FlowHelper.prototype, "folderName", void 0);
    __decorate([
        aurelia_framework_1.observable,
        __metadata("design:type", Object)
    ], FlowHelper.prototype, "params", void 0);
    return FlowHelper;
}());
var FlowUploader = exports.FlowUploader = (function () {
    function FlowUploader(logger, eventAggregator, taskQueue, box, userService, i18n, fileStorageService) {
        this.logger = logger;
        this.eventAggregator = eventAggregator;
        this.taskQueue = taskQueue;
        this.box = box;
        this.userService = userService;
        this.i18n = i18n;
        this.fileStorageService = fileStorageService;
        this.target = this.fileStorageService.controller + "upload";
        this.allowMultipleUpload = true;
        this.confirmUploadFn = null;
        this.uploadCompleteFn = null;
        this.resizePicture = false;
        this.useUniqueName = false;
        this.autoConvert = false;
        this.allowMultipleUploadBtn = false;
        this.showOverlay = true;
        this.ignoreFileExistence = false;
        this.pictureQuality = 0.7;
        this.displayLoader = false;
        this.browseButtons = [];
    }
    FlowUploader.prototype.init = function () {
        return __awaiter(this, void 0, void 0, function () {
            var accessToken, acceptExpression;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(this.flowHelper == null)) return [3, 3];
                        return [4, this.userService.accessToken()];
                    case 1:
                        accessToken = _a.sent();
                        acceptExpression = this.getAcceptExpression();
                        this.flowHelper = new FlowHelper(this.logger, this.target, this.eventAggregator, this.allowMultipleUpload, this.confirmUploadFn, acceptExpression, this.resizePicture, this.folderName, accessToken, this.compressorOptions, this.autoConvert, this.useUniqueName, this.pictureQuality);
                        this.flowHelper.fileUploaded = function (fileUploaded) {
                            if (_this.fileUploadedFn != null)
                                _this.fileUploadedFn({ fileUploaded: fileUploaded });
                        };
                        this.flowHelper.uploadComplete = function (uploadingFiles) {
                            if (_this.uploadCompleteFn != null)
                                _this.uploadCompleteFn(uploadingFiles);
                        };
                        this.flowHelper.checkExistence = function (file) {
                            return _this.checkExistence(file);
                        };
                        this.flowHelper.fileAdded = function (file) {
                            return _this.internalFileAdded(file);
                        };
                        this.flowHelper.showLoader = function (value) { return _this.showLoader(value); };
                        return [4, this.uploadButtonChanged()];
                    case 2:
                        _a.sent();
                        _a.label = 3;
                    case 3: return [2];
                }
            });
        });
    };
    FlowUploader.prototype.attached = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                this.taskQueue.queueMicroTask(function () { return __awaiter(_this, void 0, void 0, function () {
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0: return [4, this.init()];
                            case 1:
                                _a.sent();
                                if (this.dropzone != null) {
                                    this.dropzone.classList.add("dropzone");
                                    this.highlightDropzones();
                                    this.flowHelper.assignDrop(this.dropzone);
                                }
                                return [4, this.uploadButtonChanged()];
                            case 2:
                                _a.sent();
                                return [2];
                        }
                    });
                }); });
                return [2];
            });
        });
    };
    FlowUploader.prototype.showLoader = function (value) {
        this.displayLoader = value;
    };
    FlowUploader.prototype.highlightDropzones = function () {
        var _this = this;
        var overlay = $(this.dropzoneOverlay);
        $(document).bind('dragover', function (e) {
            var dropZone = $(_this.dropzone);
            var foundDropzone;
            var timeout = _this.dropZoneTimeout;
            if (!timeout) {
                dropZone.addClass('hover');
            }
            else {
                clearTimeout(timeout);
            }
            var found = false, node = e.target;
            e.originalEvent.dataTransfer.dropEffect = 'copy';
            do {
                if ($(node).hasClass('dropzone') && node == _this.dropzone) {
                    found = true;
                    foundDropzone = $(node);
                    break;
                }
                node = node.parentNode;
            } while (node != null);
            if (found) {
                dropZone.removeClass('in');
                foundDropzone.addClass('in');
                overlay.addClass('hover');
            }
            else {
                dropZone.removeClass("in");
                overlay.removeClass('hover');
            }
            _this.dropZoneTimeout = setTimeout(function () {
                _this.dropZoneTimeout = null;
                dropZone.removeClass('in hover');
                overlay.removeClass('hover');
            }, 100);
        });
        $(window).on('dragenter', function (e) {
            e.preventDefault();
        });
    };
    FlowUploader.prototype.checkExistence = function (file) {
        return __awaiter(this, void 0, void 0, function () {
            var fileName, exists, replaceLabel, duplicateLabel, cancelLabel;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (this.ignoreFileExistence) {
                            return [2, ExistenceAction.Replace];
                        }
                        fileName = (this.folderName != null && this.folderName.trim().length > 0) ? this.folderName + "/" + file.name : file.name;
                        return [4, this.fileStorageService.exists(fileName)];
                    case 1:
                        exists = _a.sent();
                        if (!exists) return [3, 3];
                        replaceLabel = this.i18n.tr("general.replace", { ns: "common" });
                        duplicateLabel = this.i18n.tr("general.duplicate", { ns: "common" });
                        cancelLabel = this.i18n.tr("general.cancel", { ns: "common" });
                        return [4, this.box.showQuestion(this.i18n.tr('fileUpload.fileAlreadyExists', { ns: "common", fileName: file.name }), this.i18n.tr('fileUpload.existingFile', { ns: "common" }), [
                                {
                                    label: cancelLabel,
                                    title: cancelLabel,
                                    theme: 'dark',
                                    type: 'ghost',
                                    fn: function (thisBox) {
                                        thisBox.controller.ok(ExistenceAction.Cancel);
                                        _this.showLoader(false);
                                    }
                                },
                                {
                                    label: duplicateLabel,
                                    title: duplicateLabel,
                                    theme: 'primary',
                                    type: 'solid',
                                    fn: function (thisBox) {
                                        thisBox.controller.ok(ExistenceAction.Duplicate);
                                    }
                                },
                                {
                                    label: replaceLabel,
                                    title: replaceLabel,
                                    theme: 'primary',
                                    type: 'solid',
                                    fn: function (thisBox) {
                                        thisBox.controller.ok(ExistenceAction.Replace);
                                    }
                                }
                            ]).whenClosed(function (dialogResult) {
                                if (!dialogResult.wasCancelled) {
                                    return dialogResult.output;
                                }
                                return ExistenceAction.Cancel;
                            })];
                    case 2: return [2, _a.sent()];
                    case 3: return [2, ExistenceAction.None];
                }
            });
        });
    };
    FlowUploader.prototype.internalFileAdded = function (file) {
        return __awaiter(this, void 0, void 0, function () {
            var createdLinkEntity;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(this.fileAddedFn != null)) return [3, 2];
                        return [4, this.fileAddedFn(file)];
                    case 1:
                        createdLinkEntity = _a.sent();
                        if (createdLinkEntity != null) {
                            createdLinkEntity.flowObj = file;
                            file.linkEntity = createdLinkEntity;
                        }
                        else {
                            console.warn("Flow-Uploader: FileAdded function handler do not return a link entity");
                        }
                        _a.label = 2;
                    case 2: return [2];
                }
            });
        });
    };
    FlowUploader.prototype.getAcceptExpression = function () {
        if (this.accept == null || this.accept.length == 0)
            return constants_1.Extensions.all;
        if (constants_1.Extensions[this.accept] != null)
            return constants_1.Extensions[this.accept];
        else
            return this.accept;
    };
    FlowUploader.prototype.uploadButtonChanged = function () {
        return __awaiter(this, void 0, void 0, function () {
            var acceptExpression, attrs;
            var _this = this;
            return __generator(this, function (_a) {
                if (this.uploadButton != null && this.flowHelper != null) {
                    if (this.allowMultipleUploadBtn) {
                        this.browseButtonAssigned = this.browseButtons.findIndex(function (x) { return x == _this.uploadButton; }) > -1;
                    }
                    if (!this.browseButtonAssigned) {
                        acceptExpression = this.getAcceptExpression();
                        attrs = {
                            accept: this.buildAcceptWithAndroidWorkaround(acceptExpression)
                        };
                        this.flowHelper.assignBrowse(this.uploadButton, attrs);
                        this.browseButtonAssigned = true;
                        this.browseButtons.push(this.uploadButton);
                    }
                }
                return [2];
            });
        });
    };
    FlowUploader.prototype.folderNameChanged = function () {
        if (this.folderName != null && this.folderName.trim().length > 0 && this.flowHelper != null) {
            this.flowHelper.folderName = this.folderName;
        }
    };
    FlowUploader.prototype.resizePictureChanged = function (newValue, oldValue) {
        if (newValue != null && newValue != oldValue && this.flowHelper != null) {
            this.flowHelper.resizePicture = newValue;
        }
    };
    FlowUploader.prototype.buildAcceptWithAndroidWorkaround = function (originalAccept) {
        var imageExtensions = /\.(jpe?g|png|gif|webp|bmp|heic|heif)/i;
        if (imageExtensions.test(originalAccept)) {
            return "".concat(originalAccept, ",android/allowCamera");
        }
        return originalAccept;
    };
    __decorate([
        (0, aurelia_framework_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.twoWay }),
        __metadata("design:type", Object)
    ], FlowUploader.prototype, "value", void 0);
    __decorate([
        aurelia_framework_1.bindable,
        __metadata("design:type", HTMLElement)
    ], FlowUploader.prototype, "dropzone", void 0);
    __decorate([
        aurelia_framework_1.bindable,
        __metadata("design:type", String)
    ], FlowUploader.prototype, "target", void 0);
    __decorate([
        aurelia_framework_1.bindable,
        __metadata("design:type", String)
    ], FlowUploader.prototype, "hintText", void 0);
    __decorate([
        aurelia_framework_1.bindable,
        __metadata("design:type", HTMLElement)
    ], FlowUploader.prototype, "uploadButton", void 0);
    __decorate([
        aurelia_framework_1.bindable,
        __metadata("design:type", Boolean)
    ], FlowUploader.prototype, "allowMultipleUpload", void 0);
    __decorate([
        aurelia_framework_1.bindable,
        __metadata("design:type", String)
    ], FlowUploader.prototype, "accept", void 0);
    __decorate([
        aurelia_framework_1.bindable,
        __metadata("design:type", Function)
    ], FlowUploader.prototype, "fileUploadedFn", void 0);
    __decorate([
        aurelia_framework_1.bindable,
        __metadata("design:type", Function)
    ], FlowUploader.prototype, "confirmUploadFn", void 0);
    __decorate([
        aurelia_framework_1.bindable,
        __metadata("design:type", Function)
    ], FlowUploader.prototype, "fileAddedFn", void 0);
    __decorate([
        aurelia_framework_1.bindable,
        __metadata("design:type", Function)
    ], FlowUploader.prototype, "uploadCompleteFn", void 0);
    __decorate([
        aurelia_framework_1.bindable,
        __metadata("design:type", Boolean)
    ], FlowUploader.prototype, "resizePicture", void 0);
    __decorate([
        aurelia_framework_1.bindable,
        __metadata("design:type", String)
    ], FlowUploader.prototype, "folderName", void 0);
    __decorate([
        (0, aurelia_framework_1.bindable)({ bindingMode: aurelia_framework_1.bindingMode.oneTime }),
        __metadata("design:type", Boolean)
    ], FlowUploader.prototype, "useUniqueName", void 0);
    __decorate([
        aurelia_framework_1.bindable,
        __metadata("design:type", Object)
    ], FlowUploader.prototype, "compressorOptions", void 0);
    __decorate([
        aurelia_framework_1.bindable,
        __metadata("design:type", Boolean)
    ], FlowUploader.prototype, "autoConvert", void 0);
    __decorate([
        aurelia_framework_1.bindable,
        __metadata("design:type", Boolean)
    ], FlowUploader.prototype, "allowMultipleUploadBtn", void 0);
    __decorate([
        aurelia_framework_1.bindable,
        __metadata("design:type", Boolean)
    ], FlowUploader.prototype, "showOverlay", void 0);
    __decorate([
        aurelia_framework_1.bindable,
        __metadata("design:type", Boolean)
    ], FlowUploader.prototype, "ignoreFileExistence", void 0);
    __decorate([
        aurelia_framework_1.bindable,
        __metadata("design:type", Number)
    ], FlowUploader.prototype, "pictureQuality", void 0);
    FlowUploader = __decorate([
        aurelia_framework_1.autoinject,
        (0, aurelia_framework_1.inlineView)("<template>\n        <slot></slot>\n        <div show.bind=\"showOverlay\" ref=\"dropzoneOverlay\" class=\"overlay\">\n            <div style=\"display: table-cell; vertical-align: middle; text-align: center\"><h5>${hintText}</h5></div>\n        </div>\n        <div show.bind=\"displayLoader\" class=\"flow_uploader__loader\">\n          <ui-loader></ui-loader>\n        </div>\n    </template>"),
        __metadata("design:paramtypes", [custom_logger_1.CustomLogger, aurelia_event_aggregator_1.EventAggregator, aurelia_framework_1.TaskQueue, box_1.Box, auth_service_1.AuthService, aurelia_i18n_1.I18N, file_storage_service_1.RemoteFileStorage.Service])
    ], FlowUploader);
    return FlowUploader;
}());

//# sourceMappingURL=flow-uploader.js.map
