"use strict";
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 };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
var Renderables_1 = require("../Renderables");
var Canvas_1 = require("../../support/Canvas");
var Navigator_1 = require("../../support/Navigator");
var Files_1 = require("../../support/Files");
var InputContainer_1 = require("../../support/InputContainer");
/**
 * Implementation of the 'camera' markup element.
 * A HTML video element is used to create a camera.
 * For CSS manipulations the following classes are added:
 *  lto-camera: the camera container
 *  lto-take-photo: is used for taking a photo. The photo will be displayed in the canvas below the video element
 *  lto-reset-photo: is enabled when photo is taken. A click on this div, resets the camera
 *
 * @see {@link IRenderable}
 */
var Camera = /** @class */ (function () {
    function Camera(message) {
        this.maxCanvasSize = 640;
        this.spec = message;
    }
    /**
     * @inheritDoc
     */
    Camera.prototype.render = function (renderer, isNested) {
        var _this = this;
        var wrapper = document.createElement("div");
        wrapper.classList.add("lto-camera");
        wrapper.setAttribute("name", this.spec.name || "");
        InputContainer_1.InputContainer.setRequiredAttribute(wrapper, this.spec.required);
        var error = document.createElement("div");
        error.classList.add("lto-error");
        error.style.display = "none";
        wrapper.appendChild(error);
        var video = document.createElement("video");
        wrapper.appendChild(video);
        var canvas = document.createElement("canvas");
        wrapper.appendChild(canvas);
        var controlWrapper = document.createElement("div");
        var photoButton = document.createElement("div");
        photoButton.classList.add("lto-take-photo", "lto-disabled");
        controlWrapper.appendChild(photoButton);
        var resetButton = document.createElement("div");
        resetButton.classList.add("lto-reset-photo", "lto-disabled");
        controlWrapper.appendChild(resetButton);
        wrapper.appendChild(controlWrapper);
        var elements = (this.spec.elements || []).map(function (e) { return renderer.render(e, _this); });
        elements.forEach(function (e) { return e.forEach(function (x) { return wrapper.appendChild(x); }); });
        this.initCamera(wrapper);
        this.activatePhotoButton(wrapper);
        return wrapper;
    };
    Camera.prototype.initCamera = function (wrapper) {
        var _this = this;
        var video = wrapper.querySelector("video");
        var canvas = wrapper.querySelector("canvas");
        wrapper.classList.remove("lto-not-available");
        var userMedia = Navigator_1.Navigator.getUserVideoMedia();
        if (userMedia == null) {
            return;
        }
        userMedia.then(function (mediaStream) {
            _this.mediaStream = mediaStream;
            video.srcObject = _this.mediaStream;
            video.play()
                .then(function () {
                if (!video.classList.contains("lto-active")) {
                    video.classList.add("lto-active");
                }
                canvas.classList.remove("lto-active");
            });
        })
            .catch(function (error) {
            console.error(error);
            video.classList.remove("lto-active");
            canvas.classList.remove("lto-active");
            var errorWrapper = wrapper.querySelector(".lto-error");
            errorWrapper.style.display = "block";
            wrapper.classList.add("lto-not-available");
            Camera.deactivateClick(wrapper.querySelector(".lto-take-photo"));
            _this.activateResetButton(wrapper);
        });
    };
    Camera.prototype.takePhoto = function (wrapper) {
        var canvas = wrapper.querySelector("canvas");
        var video = wrapper.querySelector("video");
        Canvas_1.drawCanvas(canvas, video, this.mediaStream || new MediaStream(), this.maxCanvasSize);
        this.stopCamera(wrapper);
    };
    Camera.prototype.stopCamera = function (wrapper) {
        var video = wrapper.querySelector("video");
        video.classList.remove("lto-active");
        var canvas = wrapper.querySelector("canvas");
        canvas.classList.add("lto-active");
        this.mediaStream.getTracks().forEach(function (track) { return track.stop(); });
    };
    Camera.prototype.activatePhotoButton = function (wrapper) {
        var _this = this;
        var photoButton = wrapper.querySelector(".lto-take-photo");
        photoButton.onclick = function () {
            _this.takePhoto(wrapper);
            var canvas = wrapper.querySelector("canvas");
            wrapper.setAttribute("data-value", JSON.stringify({
                data: canvas.toDataURL().split(",")[1],
                fileExtension: "png",
                mimeType: "image/png"
            }));
            if (_this.spec.maxCompressSize) {
                console.info("Using image compression with " + _this.spec.maxCompressSize + "MB");
                _this.compressCameraImage(canvas, wrapper)
                    .catch(function (reason) { return console.error("Unable to compress image: " + reason); });
            }
            _this.activateResetButton(wrapper);
            Camera.deactivateClick(photoButton);
        };
        photoButton.classList.toggle("lto-disabled");
    };
    Camera.prototype.compressCameraImage = function (canvas, wrapper) {
        return __awaiter(this, void 0, void 0, function () {
            var imageCompression;
            var _this = this;
            return __generator(this, function (_a) {
                console.info("Attempt to comress image with max. compress size " + this.spec.maxCompressSize);
                imageCompression = typeof window !== "undefined" ? require("browser-image-compression/dist/browser-image-compression") : null;
                if (!imageCompression)
                    return [2 /*return*/];
                imageCompression.getFilefromDataUrl(canvas.toDataURL())
                    .then(function (uncompressedFile) {
                    console.debug("Got file from data url");
                    if (!uncompressedFile)
                        return;
                    var options = {
                        maxSizeMB: _this.spec.maxCompressSize,
                        useWebWorker: false,
                        maxWidthOrHeight: 974
                    };
                    imageCompression.default(uncompressedFile, options)
                        .then(function (compressedFile) {
                        console.debug("Compressed object is instanceof Blob: " + (compressedFile instanceof Blob));
                        console.info("Compressed to size " + compressedFile.size / 1024 / 1024 + " MB");
                        wrapper.setAttribute("value", JSON.stringify({
                            data: Files_1.getBase64FromFile(compressedFile),
                            fileExtension: "png",
                            mimeType: "image/png"
                        }));
                    }).catch(function (reason) { return console.error("Unable to compress file: " + reason); });
                })
                    .catch(function (reason) { return console.error("Unable to get file from data url: " + reason); });
                return [2 /*return*/];
            });
        });
    };
    Camera.prototype.activateResetButton = function (wrapper) {
        var _this = this;
        var resetButton = wrapper.querySelector(".lto-reset-photo");
        resetButton.onclick = function () {
            wrapper.removeAttribute("data-value");
            var errorWrapper = wrapper.querySelector(".lto-error");
            errorWrapper.style.display = "none";
            _this.initCamera(wrapper);
            var canvas = wrapper.querySelector("canvas");
            canvas.getContext("2d").clearRect(0, 0, canvas.width, canvas.height);
            _this.activatePhotoButton(wrapper);
            Camera.deactivateClick(resetButton);
        };
        resetButton.classList.toggle("lto-disabled");
    };
    Camera.deactivateClick = function (element) {
        element.onclick = null;
        element.classList.toggle("lto-disabled");
    };
    return Camera;
}());
exports.Camera = Camera;
Renderables_1.default.register("camera", Camera);
//# sourceMappingURL=index.js.map