"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 { Cube} from "../../geometry/Figure.js";
import GeometryPainter from "../../geometry/GeometryPainter.js";
import {TrackballCamera, registerCameraEvents} from "../../modules/Trackballcamera.js";
import V3 from "../../modules/V3.js";

/**
 * Dos cubos: vértices compartidos y vértices independientes.
 * @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 cubeFigure = new Cube(1.2);
    let lightPosition = [2, 3, 3, 0];
    let diffuseUniforms = { u_light_position: lightPosition };
    let redUniform = {u_color: [1,.3,.1,1]};
    let blueUniform = {u_color: [.1,.4,1,1]};
    
    let redCubeTranslation = M4.translate(1.5,0,0);
    let redCube = new GeometryPainter(gl, new Diffuse(gl, WebGL, cubeFigure, redUniform), 
                                      redCubeTranslation);
    cubeFigure.byIndices = true;
    let blueCubeTranslation = M4.translate(-1.5,0,0);
    let blueCube = new GeometryPainter(gl, new Diffuse(gl, WebGL, cubeFigure, blueUniform), 
                                       blueCubeTranslation);  
    var fov = 90;
    if(window.innerWidth < window.innerHeight)
        fov = 120;

    let zNear = 1;
    let zFar = 2000;
    var pos = new V3(0,1.3,3);
    let camera = new TrackballCamera(pos);
    
    Utils.resize(canvas);
    
    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;
        
        blueCube.draw(gl, viewMatrix, projectionMatrix, diffuseUniforms);       
        redCube.draw(gl, viewMatrix, projectionMatrix, diffuseUniforms);       
    }
}