import { assetManager, getError } from "cc";

export function initFixed() {
    console.log("initFixed");
    assetManager.downloader.downloadDomImage = function downloadDomImage(
        url: string,
        options: Record<string, any>,
        onComplete: ((err: Error | null, data?: HTMLImageElement | null) => void),
    ): HTMLImageElement {
        console.log("downloadDomImage",url);
        
        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';
            // 检查图片是否包含crossOrigin属性
            if (img.hasAttribute('crossOrigin')) {
                // 移除crossOrigin属性
                img.removeAttribute('crossOrigin');
            }
        }

        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);
    });
}

initFixed();
