export class Texture{
    constructor(public texture: GPUTexture, public sampler: GPUSampler){}

    public static async createTexture(device: GPUDevice, image: HTMLImageElement)
    : Promise<Texture>
    {
        const texture = device.createTexture({
            size: { width: image.width, height: image.height},
            format: "rgba8unorm",
            usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT
        });

        const data = await createImageBitmap(image );

        device.queue.copyExternalImageToTexture(
            { source: data },
            { texture: texture  },
            { width: image.width, height: image.height }
        );

        const sampler = device.createSampler({
            magFilter: "linear",
            minFilter: "linear",
        });

        return new Texture(texture, sampler);
    }

    public static async createTextureFromUrl(device: GPUDevice, url: string): Promise<Texture>
    {
        const imagePromise  = new Promise<HTMLImageElement>((resolve, reject) => {
            const img = new Image();
            img.src = url;
            img.onload = () => resolve(img);
            img.onerror = () => {
                console.error('Failed to load image from url: ' + url);
                reject();
            }
        });

        const image = await imagePromise;
        return await Texture.createTexture(device, image);
    }
    
}