import { assetManager, getError } from "cc";

export function initFixed() {
    assetManager.downloader.downloadDomImage = function downloadDomImage(
        url: string,
        options: Record<string, any>,
        onComplete: ((err: Error | null, data?: HTMLImageElement | null) => void),
    ): HTMLImageElement {
        const img = new window.Image();

        // NOTE: on xiaomi platform, we need to force setting img.crossOrigin as 'anonymous'
        if (location.protocol !== "file:") {
            // img.crossOrigin = 'anonymous';
        }

        if(location.hostname == "localhost"){
            img.crossOrigin = 'anonymous';
        }

        function loadCallback(): void {
            img.removeEventListener("load", loadCallback);
            img.removeEventListener("error", errorCallback);
            if (onComplete) { onComplete(null, img); }
        }

        function errorCallback(): void {
            img.removeEventListener("load", loadCallback);
            img.removeEventListener("error", errorCallback);
            if (onComplete) { onComplete(new Error(getError(4930, url))); }
        }

        img.addEventListener("load", loadCallback);
        img.addEventListener("error", errorCallback);
        img.src = url;
        return img;
    };

    const types = [
        ".png",
        ".jpg",
        ".bmp",
        ".jpeg",
        ".gif",
        ".ico",
        ".tiff",
        ".webp",
        ".image",
        ".pvr",
        ".pkm",
        ".astc",
    ];
    types.forEach((type) => {
        assetManager.downloader.register(type, assetManager.downloader.downloadDomImage);
    });
}
