"use strict";

import {resize, Select, addLabel, scaleToFitContainer} from "../../modules/HTMLUtils.js";
import WebGL from "../../modules/WebGLUtils.js";
import M4 from "../../modules/M4.js";
import Texture from "../../materials/Texture.js";
import {Plane} from "../../geometry/Figure.js";
import {TrackballCamera, registerCameraEvents} from "../../modules/Trackballcamera.js";
import V3 from "../../modules/V3.js";

/**
 * Pirámide de mipmaps.
 * @author Melissa Méndez Servín.
 */
window.addEventListener("load", main);

function main(){
    var canvas = document.getElementById("gl_canvas");
    var gl = WebGL.init(canvas);
    if(!gl) return;
   
    let planeFigure = new Plane();
    let srcTexture = "../../../images/capitulo_07/textures/Tiles093_1K_Color.jpg";
    let material =  new Texture(gl, WebGL, planeFigure, srcTexture, draw); 
   
    var pos = new V3(0,.7,1.1);
    let camera = new TrackballCamera(pos);
    camera.setZoomConfig(1.5, 1);
    var translation;
    var modelMatrix;
    var modelViewMatrix;
    
    gl.enable(gl.DEPTH_TEST);
    
    gl.clearColor(0, 0, 0, 0);
    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);

    window.addEventListener('resize', draw);
    registerCameraEvents(camera, canvas, draw);
    
    draw();

    function draw(loadedTexture){        
        resize(canvas);
        var {width, height} = gl.canvas;

        gl.viewport(0, 0, width, height);
        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
        
        gl.useProgram(material.program);
        gl.bindVertexArray(material.vao);

        let aspect = width/height;
        var projectionMatrix = M4.perspective(75, aspect, .1, 100);
        
       if(loadedTexture){
           material.uniforms.u_texture = {id:0, texture: loadedTexture};
       }
        var viewMatrix = camera.getMatrix();
        var s = 1;
        var t = 0;
        for(var i= 0; i < 15; i ++){
            t = (i == 0) ? 0 : 1-1/(i+1);
            translation = M4.translate(0,-.25 + t,0);

            modelMatrix = M4.multiply( translation, M4.multiply(M4.rotateY(25), M4.rotateX(-90)));
            
            modelMatrix = M4.multiply(modelMatrix, M4.scale(s,s,s));
            modelViewMatrix = M4.multiply(viewMatrix, modelMatrix);
            s *= .5;
            material.uniforms.u_PVM_matrix = M4.multiply(projectionMatrix, modelViewMatrix); 
       
            material.setUniforms(material.uniforms);
            
            gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, material.indexBuffer);
            gl.drawElements( gl.TRIANGLES, material.numIndices,  gl.UNSIGNED_SHORT, 0);
        }
        

        gl.bindBuffer(gl.ARRAY_BUFFER, null);      
    }
} 