"use strict";

import * as Utils from "../../modules/HTMLUtils.js";
import WebGL from "../../modules/WebGLUtils.js";
import M4 from "../../modules/M4.js";
import Diffuse from "../../materials/Diffuse.js";
import SolidColor from "../../materials/SolidColor.js";
import GeometryPainter from "../../geometry/GeometryPainter.js";
import {TrackballCamera, registerCameraEvents} from "../../modules/Trackballcamera.js";
import V3 from "../../modules/V3.js";
import Bunny993 from "../../geometry/Bunny993.js";

/**
 * Ejemplo de malla triangular. Modelo Bunny de Stanford University.
 * @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 geometryFigure = new Bunny993();
   
    let lightPosition = [2, 3, 3, 0];
    let diffuseUniforms = { u_light_position: lightPosition };
    let uniform = {u_color: [.8,.8,.8,1]};
    let transform = M4.multiply(M4.translate(0,-.35,0), M4.multiply(M4.rotateY(15),M4.scale(2,2,2)));
    //let figure = new GeometryPainter(gl, new Diffuse(gl, WebGL, geometryFigure, uniform), transform);
    let wireframe = new GeometryPainter(gl, new SolidColor(gl, WebGL, geometryFigure, [.24,.24,.24,1]), transform);

    var fov = 80;
    if(window.innerWidth < window.innerHeight)
        fov = 120;

    let zNear = .1;
    let zFar = 2000;
    let camera = new TrackballCamera( new V3(0,0,4));
    camera.setZoomConfig(5,3);
    
    Utils.resize(canvas);
    
    let container = document.getElementById("container");
    let ccLabel = new Utils.TextBox(container, { right: 1, bottom: 0}, "<i>Bunny</i>. Modelo obtenido de <i>Stanford University <br>Computer Graphics Laboratory</i>.");
    ccLabel.setPosition({top: 1, left: 1});

    gl.enable(gl.DEPTH_TEST);
    gl.enable(gl.CULL_FACE);
    
    gl.clearColor(0, 0, 0, 0);

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

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

        gl.viewport(0, 0, width, height);
        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
             
        let aspect = width/height;
        var projectionMatrix = M4.perspective(fov, aspect, zNear, zFar);

        let viewMatrix = camera.getMatrix();
        var lightPos = M4.multiplyVector(viewMatrix, lightPosition);
        diffuseUniforms.u_light_position = lightPos;
              
        //figure.draw(gl, viewMatrix, projectionMatrix, diffuseUniforms);    
        wireframe.drawWireframe(gl, viewMatrix, projectionMatrix);   
    }
}