import libheif from "libheif-js";
var supportedMIMETypes = ["image/png", "image/jpeg"];
var utils = {
    blobToDataURL: function (blob) {
        return new Promise(function (resolve, reject) {
            var reader = new FileReader();
            reader.onerror = function () {
                reject("ERR_DOM Error on converting blob to data URL");
            };
            reader.onload = function (e) {
                resolve(reader.result);
            };
            reader.readAsDataURL(blob);
        });
    },
    dataURItoBlob: function (dataURI) {
        try {
            var byteString = atob(dataURI.split(",")[1]);
            var mimeString = dataURI.split(",")[0].split(":")[1].split(";")[0];
            var ab = new ArrayBuffer(byteString.length);
            var ia = new Uint8Array(ab);
            for (var i = 0; i < byteString.length; i++) {
                ia[i] = byteString.charCodeAt(i);
            }
            var blob = new Blob([ab], { type: mimeString });
            return blob;
        }
        catch (e) {
            return "ERR_DOM Error on converting data URI to blob " + e &&
                e.toString
                ? e.toString()
                : e;
        }
    },
    imageDataToBlob: function (_a) {
        var imageData = _a.imageData, _b = _a.toType, toType = _b === void 0 ? "image/png" : _b, _c = _a.quality, quality = _c === void 0 ? 0.92 : _c;
        if (quality > 1 || quality < 0) {
            quality = 0.92;
        }
        if (supportedMIMETypes.indexOf(toType) === -1) {
            toType = "image/png";
        }
        return new Promise(function (resolve, reject) {
            var canvas = null;
            try {
                canvas = document.createElement("canvas");
            }
            catch (e) { }
            if (!canvas) {
                return reject("ERR_CANVAS Error on converting imagedata to blob: Could not create canvas element");
            }
            canvas.width = imageData.width;
            canvas.height = imageData.height;
            var ctx = canvas.getContext("2d");
            if (!ctx) {
                return reject("ERR_CANVAS Error on converting imagedata to blob: Could not get canvas context");
            }
            ctx.putImageData(imageData, 0, 0);
            canvas.toBlob(function (blob) {
                if (!blob) {
                    return reject("ERR_CANVAS Error on converting imagedata to blob: Could not get blob from canvas");
                }
                return resolve(blob);
            }, toType, quality);
        });
    },
    otherImageType: function (buffer) {
        var arr = new Uint8Array(buffer).subarray(0, 4);
        var header = "";
        for (var i = 0; i < arr.length; i++) {
            header = header + arr[i].toString(16);
        }
        switch (header) {
            case "89504e47":
                return "image/png";
            case "ffd8ffe0":
            case "ffd8ffe1":
            case "ffd8ffe2":
            case "ffd8ffe3":
            case "ffd8ffe8":
                return "image/jpeg";
            default:
                return false;
        }
    },
    error: function (message) {
        var code = 0;
        if (!message) {
            message = "ERR_UNKNOWN";
        }
        else if (typeof message !== "string") {
            if (message.toString) {
                message = message.toString();
            }
            else {
                message = JSON.stringify(message);
            }
        }
        var headers = [
            "ERR_USER",
            "ERR_LIBHEIF",
            "ERR_GIF",
            "ERR_DOM",
            "ERR_CANVAS",
        ];
        for (var index = 0; index < headers.length; index++) {
            var header = headers[index];
            if (message.indexOf(header) === 0) {
                code = index + 1;
            }
        }
        return {
            code: code,
            message: message,
        };
    },
};
function decodeBuffer(buffer) {
    return new Promise(function (resolve, reject) {
        try {
            var decoder = new libheif.HeifDecoder();
            var imagesArr = decoder.decode(buffer);
            if (!imagesArr || !imagesArr.length) {
                throw "ERR_LIBHEIF format not supported";
            }
            imagesArr = imagesArr.filter(function (x) {
                var valid = true;
                try {
                    x.get_height();
                }
                catch (e) {
                    valid = false;
                }
                return valid;
            });
            if (!imagesArr.length) {
                throw "ERR_LIBHEIF Heic doesn't contain valid images";
            }
            processSingleImage(imagesArr[0])
                .then(function (imageData) {
                return resolve(imageData);
            })
                .catch(function (e) {
                return reject(e && e.toString ? e.toString() : e);
            });
        }
        catch (e) {
            return reject(e && e.toString ? e.toString() : e);
        }
    });
}
function processSingleImage(image) {
    return new Promise(function (resolve, reject) {
        var w = image.get_width();
        var h = image.get_height();
        var whiteImage = new ImageData(w, h);
        for (var i = 0; i < w * h; i++) {
            whiteImage.data[i * 4 + 3] = 255;
        }
        image.display(whiteImage, function (imageData) {
            if (!imageData) {
                return reject("ERR_LIBHEIF Error while processing single image and generating image data, could not ensure image");
            }
            return resolve(imageData);
        });
    });
}
function heic2any(_a) {
    var blob = _a.blob, _b = _a.toType, toType = _b === void 0 ? "image/png" : _b, _c = _a.quality, quality = _c === void 0 ? 0.92 : _c;
    return new Promise(function (resolve, reject) {
        if (!(blob instanceof Blob)) {
            utils.error("ERR_USER library only accepts BLOBs as input");
        }
        if (typeof quality !== "number") {
            utils.error("ERR_USER \"quality\" parameter should be of type \"number\"");
        }
        var reader = new FileReader();
        reader.onload = function (e) {
            var buffer = e.target.result;
            var otherImageType = utils.otherImageType(buffer);
            if (otherImageType) {
                return reject(utils.error("ERR_USER Image is already browser readable: ".concat(otherImageType)));
            }
            decodeBuffer(buffer)
                .then(function (imageData) {
                return utils.imageDataToBlob({
                    imageData: imageData,
                    toType: toType,
                    quality: quality,
                });
            })
                .then(function (blob) {
                resolve(blob);
            })
                .catch(function (e) {
                reject(utils.error(e));
            });
        };
        reader.readAsArrayBuffer(blob);
    });
}
export default heic2any;

//# sourceMappingURL=heic2any.js.map
