/**
 * Programa de sombreado del mapeo de una textura sobre una superficie 2D.
 * @author Melissa Méndez Servín.
 */
export default class Texture2D{
   
    constructor(gl, WebGL, attributes, srcTexture){
        var vsh = `#version 300 es
            uniform mat3 u_matrix;
            
            in vec2 a_position;
            in vec2 a_texcoord;
            
            out vec2 texcoord;

            void main(){
                texcoord = a_texcoord;
                
                vec3 position =  u_matrix * vec3(a_position,1);
                gl_Position = vec4(position.xy, 0, 1);
            }
            `;
        var fsh = `#version 300 es
            precision highp float;

            uniform sampler2D u_texture;

            in vec2 texcoord;
            
            out vec4 glColor;
            
            void main(){
                glColor = texture(u_texture, texcoord);
            }
            `;
        if (WebGL.programs["Texture2D"])
            this.program = WebGL.programs["Texture2D"];
        else
            this.program = WebGL.createProgram(gl, vsh, fsh, "Texture2D");

        this.vao = WebGL.setVAOAndAttributes(gl, this.program, attributes);  
        this.setUniforms = WebGL.setUniforms(gl, this.program);
        this.texture = create2DTexture(gl, srcTexture);
    }
}
/**
 * 
 * @param {*} gl 
 * @param {*} src 
 */
function create2DTexture(gl, src){
        var texture = gl.createTexture();

        gl.bindTexture(gl.TEXTURE_2D, texture);
        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE,
            new Uint8Array([22, 164, 133, 255]));
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
        var textureInfo = { texture: texture, width : 0,  height: 0};
                
        var img = new Image();
        img.addEventListener('load', function() {
            textureInfo.width = img.width;
            textureInfo.height = img.height;
            
            gl.bindTexture(gl.TEXTURE_2D, texture);
            gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img);
            gl.generateMipmap(gl.TEXTURE_2D);
        });
        img.addEventListener("error", (evt) => {
            throw `Error loading image: ${img.src}`;
        });
        img.src = src;
        return textureInfo;
    }