import "./apng-canvas/main";

export default class ApngLoader {
    async load(img) {
        let anim = await APNG.parseURL(img.src);

        const canvas = document.createElement("canvas");
        canvas.width = anim.width;
        canvas.height = anim.height;

        var imgWidth = "",
            imgHeight = "",
            val = 0,
            unit = "";

        if (img.style.width != "" && img.style.width != "auto") {
            imgWidth = img.style.width;
        } else if (img.hasAttribute("width")) {
            imgWidth = img.getAttribute("width") + "px";
        }
        if (img.style.height != "" && img.style.height != "auto") {
            imgHeight = img.style.height;
        } else if (img.hasAttribute("height")) {
            imgHeight = img.getAttribute("height") + "px";
        }
        if (imgWidth != "" && imgHeight == "") {
            val = parseFloat(imgWidth);
            unit = imgWidth.match(/\D+$/)[0];
            imgHeight = Math.round((canvas.height * val) / canvas.width) + unit;
        }
        if (imgHeight != "" && imgWidth == "") {
            val = parseFloat(imgHeight);
            unit = imgHeight.match(/\D+$/)[0];
            imgWidth = Math.round((canvas.width * val) / canvas.height) + unit;
        }
        canvas.style.width = imgWidth;
        canvas.style.height = imgHeight;
        const context = canvas.getContext("2d");
        anim.addContext(context);
        anim.play();
        return { canvas, context };
    }
}
