import { ClampToEdgeWrapping, DataTexture, RGBAFormat, UnsignedByteType } from 'three';
import { assert } from "../../../../core/assert.js";
import { Sampler2D } from "./Sampler2D.js";
import { sampler2d_transfer_data } from "./sampler2d_transfer_data.js";


/**
 *
 * @param {Sampler2D} sampler
 * @return {DataTexture}
 */
function sampler2d_to_texture(sampler) {
    assert.defined(sampler, 'sampler');

    const result = new DataTexture();
    result.format = RGBAFormat;

    let data;

    if (sampler.itemSize === 4) {
        //no transformation, use a direct reference
        data = sampler.data;

    } else {
        const dest = Sampler2D.uint8(4, sampler.width, sampler.height);
        sampler2d_transfer_data(sampler, dest);

        data = dest.data;
    }

    result.type = UnsignedByteType;
    result.flipY = true;
    result.image = { data: data, width: sampler.width, height: sampler.height };

    result.wrapS = ClampToEdgeWrapping;
    result.wrapT = ClampToEdgeWrapping;

    // possibly not-power-of-two
    result.generateMipmaps = false;

    result.repeat.set(1, 1);
    result.needsUpdate = true;

    result.anisotropy = 4;

    return result;

}

export default sampler2d_to_texture;
