import { DDSLoader } from "three/examples/jsm/loaders/DDSLoader.js";
import { Asset } from "../../Asset.js";
import { cloneTexture } from "./cloneTexture.js";

export function loadDDSTexture(path, success, failure, progress) {
    function computeByteSize(texture) {
        let result = 0;
        const images = texture.image;
        for (let i = 0; i < images.length; i++) {
            const image = images[i];
            const mipmaps = image.mipmaps;
            for (let j = 0; j < mipmaps.length; j++) {
                const mipmap = mipmaps[j];
                /**
                 * @type {Uint8Array}
                 */
                const data = mipmap.data;
                result += data.length;
            }
        }
        return result;
    }

    const loader = new DDSLoader();
    loader.load(path, function (texture) {
        const byteSize = computeByteSize(texture);

        function factory() {
            return cloneTexture(texture);
        }

        const asset = new Asset(factory, byteSize);

        success(asset);

    }, progress, failure);
}
