var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    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) : new P(function (resolve) { resolve(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 (_) 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 };
    }
};
import Renderables from '../Renderables';
import { getBase64FromFile, getFileExtensionFromFile, isImageFile } from "../../support/Files";
import { InputContainer } from "../../support/InputContainer";
/**
 * Implementation of the 'upload' markup element.
 * Multiple HTML elements are used to create an upload drop area.
 * For CSS manipulations the following classes are added:
 *  lto-upload-error-label: text for error messages
 *  lto-upload-file-label: upload file text
 *  lto-upload-file-extension-label: file extension text label
 *  lto-upload-size-label: file size text label
 *  lto-upload-text-label: upload file text label
 *  lto-upload: general CSS upload class
 *
 * @see {@link IRenderable}
 */
var Upload = /** @class */ (function () {
    function Upload(spec) {
        this.errorSpan = document.createElement("span");
        this.fileSpan = document.createElement("span");
        this.dropArea = document.createElement("div");
        this.spec = spec;
    }
    /**
     * @inheritDoc
     */
    Upload.prototype.render = function (renderer, isNested) {
        var _this = this;
        var position = this.spec.position || 'left';
        InputContainer.setRequiredAttribute(this.dropArea, this.spec.required);
        var upload = document.createElement("input");
        var uploadLabel = document.createElement("label");
        var textSpan = document.createElement("span");
        var extensionSpan = document.createElement("span");
        var sizeSpan = document.createElement("span");
        this.errorSpan.className = "lto-upload-error-label";
        this.fileSpan.className = "lto-upload-file-label";
        extensionSpan.className = "lto-upload-extension-label";
        sizeSpan.className = "lto-upload-size-label";
        textSpan.className = "lto-upload-text-label";
        uploadLabel.className = "lto-upload";
        textSpan.innerText = this.spec.text || "";
        extensionSpan.innerText = this.spec.accept || "";
        sizeSpan.innerText = this.spec.maxSize.toString() || "";
        upload.type = "file";
        if (this.spec.accept) {
            var acceptArray = this.spec.accept.replace(/\s/g, '').split(",");
            upload.accept = "." + acceptArray.join(",.");
        }
        this.dropArea.classList.add("lto-drop-area", "lto-" + position);
        this.dropArea.setAttribute("name", this.spec.name || "");
        if (isNested) {
            uploadLabel.classList.add("lto-nested");
            this.dropArea.classList.add("lto-nested");
        }
        if (this.spec.id !== undefined) {
            uploadLabel.id = this.spec.id;
        }
        if (this.spec.class !== undefined) {
            this.spec.class.split(" ").forEach(function (e) {
                uploadLabel.classList.add(e);
                _this.dropArea.classList.add(e);
            });
        }
        this.dropArea.ondragover = function (ev) { return ev.preventDefault(); };
        this.dropArea.ondrop = function (ev) {
            ev.preventDefault();
            var file = null;
            if (ev.dataTransfer) {
                file = ev.dataTransfer.items ? ev.dataTransfer.items[0].getAsFile() : ev.dataTransfer.files[0];
            }
            if (file !== null) {
                _this.doValidateAndGetBase64(file);
            }
        };
        upload.onchange = function () {
            if (!upload.files || !upload.files[0]) {
                return;
            }
            var file = upload.files[0];
            if (!_this.validateFile(file.size, getFileExtensionFromFile(file))) {
                return;
            }
            _this.setFileNameToSpan(file.name).setErrorSpanTo("");
            if (!_this.spec.maxCompressSize || !isImageFile(getFileExtensionFromFile(file))) {
                _this.doValidateAndGetBase64(file);
            }
            else if (_this.spec.maxCompressSize && isImageFile(getFileExtensionFromFile(file))) {
                _this.doValidateCompressAndGetBase64(file);
            }
        };
        uploadLabel.appendChild(upload);
        uploadLabel.appendChild(textSpan);
        this.dropArea.appendChild(uploadLabel);
        this.dropArea.appendChild(extensionSpan);
        this.dropArea.appendChild(sizeSpan);
        this.dropArea.appendChild(this.fileSpan);
        this.dropArea.appendChild(this.errorSpan);
        return this.dropArea;
    };
    Upload.prototype.doValidateAndGetBase64 = function (file) {
        var _this = this;
        getBase64FromFile(file)
            .then(function (data) { return _this.setDataToValue(data, file); })
            .then(function () { return _this.setSuccessClass(); })
            .catch(function (reason) {
            console.error("Unable to get file: " + reason);
            _this.removeSuccessClass();
        });
    };
    Upload.prototype.doValidateCompressAndGetBase64 = function (file) {
        var _this = this;
        this.compressImage(file)
            .then(function (compressedFile) {
            console.debug("Compressed object is instanceof Blob: " + (compressedFile instanceof Blob));
            console.info("Compressed to size " + compressedFile.size / 1024 / 1024 + " MB");
            return getBase64FromFile(compressedFile);
        })
            .then(function (base64Data) { return _this.setDataToValue(base64Data, file); })
            .then(function () { return _this.setSuccessClass(); })
            .catch(function (reason) { return console.error("Unable to compress file: " + reason); });
    };
    Upload.prototype.setSuccessClass = function () {
        if (!this.dropArea.classList.contains("lto-success")) {
            this.dropArea.classList.add("lto-success");
        }
    };
    Upload.prototype.removeSuccessClass = function () {
        this.dropArea.classList.remove("lto-success");
    };
    Upload.prototype.setDataToValue = function (data, file) {
        this.dropArea.setAttribute("data-value", JSON.stringify({
            data: data.split(",")[1],
            fileExtension: getFileExtensionFromFile(file),
            fileName: file.name,
            mimeType: file.type
        }));
    };
    Upload.prototype.compressImage = function (file) {
        return __awaiter(this, void 0, void 0, function () {
            var imageCompression, options;
            return __generator(this, function (_a) {
                console.info("Attempt to compress file with max. compress size " + this.spec.maxCompressSize);
                imageCompression = typeof window !== "undefined" ? require("browser-image-compression/dist/browser-image-compression") : null;
                if (!imageCompression) {
                    console.error("Image compression is not available; returning uncompressed file");
                    return [2 /*return*/, file];
                }
                options = {
                    maxSizeMB: this.spec.maxCompressSize,
                    useWebWorker: false,
                    maxWidthOrHeight: 974
                };
                return [2 /*return*/, imageCompression.default(file, options)];
            });
        });
    };
    Upload.prototype.setFileNameToSpan = function (name) {
        this.fileSpan.innerText = name;
        return this;
    };
    Upload.prototype.setErrorSpanTo = function (text) {
        this.errorSpan.innerText = text;
        return this;
    };
    Upload.prototype.validateFile = function (size, extension) {
        this.setErrorSpanTo("");
        this.errorSpan.classList.remove("lto-upload-extension-error", "lto-upload-size-error");
        var extensionAllowed = true;
        var sizeAllowed = true;
        if (extension && this.spec.accept) {
            var allowedExtensions = this.spec.accept.replace(/\s/g, '').split(",");
            extensionAllowed = allowedExtensions.find(function (e) { return e === "" + extension; }) !== undefined;
            if (!extensionAllowed) {
                this.setFileNameToSpan("");
                this.errorSpan.classList.add("lto-upload-extension-error");
            }
        }
        if (size > this.spec.maxSize * 1024 * 1024) {
            this.setFileNameToSpan("");
            this.errorSpan.classList.add("lto-upload-size-error");
            sizeAllowed = false;
        }
        return sizeAllowed && extensionAllowed;
    };
    return Upload;
}());
export { Upload };
Renderables.register("upload", Upload);
//# sourceMappingURL=index.js.map