import {getDisconnectedVertices} from "../geometry/Figure.js";
/**
 * Programa de sombreado Skybox.
 * @author Melissa Méndez Servín.
 */
export default class Skybox{
    
    constructor(gl, WebGL, figure, cube_map_info, draw_callback){

        var vsh = `#version 300 es
                    uniform mat4 u_PVM_matrix;
                    uniform mat4 u_VM_matrix;
                    
                    in vec4 a_position;

                    out vec3 v_position; 

                    void main(){
                    
                        v_position =  a_position.xyz;
                        gl_Position = u_PVM_matrix * a_position;

                    }`;
        var fsh = `#version 300 es
                    precision highp float;
                    
                    uniform samplerCube u_cube_map;
                    in vec3 v_position;
                    
                    out vec4 glColor;
                
                    void main(){
                        glColor = texture(u_cube_map, v_position);
                    }`; 

        if (WebGL.programs["Skybox"])
            this.program = WebGL.programs["Skybox"];
        else
            this.program = WebGL.createProgram(gl, vsh, fsh, "Skybox");
            
        this.vertices = (figure.byIndices || figure.getNormals) ?  figure.getVertices() : getDisconnectedVertices(figure.getVertices(), figure.getFaces());
   
        let attributes = {  position: { numComponents: 3, data: this.vertices} };
        
        if(figure.byIndices){
            let vaoAndIndices = WebGL.setVAOAndAttributes(gl, this.program, attributes, figure.getFaces());
            this.vao = vaoAndIndices.vao;
            this.indexBuffer = vaoAndIndices.indexBuffer;
            this.numIndices = figure.numIndices;
        }else{
            this.vao = WebGL.setVAOAndAttributes(gl, this.program, attributes);  
            this.numElements = this.vertices.length/3;
        }
        this.setUniforms = WebGL.setUniforms(gl, this.program);

        let srcTextures = [];
        cube_map_info.forEach(element => {
            srcTextures.push(element.url);
        });
        this.texture = WebGL.loadImages(srcTextures, createTextures);
        this.uniforms = {};

        function createTextures(images){
            WebGL.createCubeMap(gl, images, cube_map_info, draw_callback);
        }
    }
}