"use strict";
import {resize, Color, Slider, hexToRgbNormalized} from "../../modules/HTMLUtils.js";
import WebGL from "../../modules/WebGLUtils.js";
import M4 from "../../modules/M4.js";
import {RectangularPrism, Cylinder} from "../../geometry/Figure.js";
import GeometryPainter from "../../geometry/GeometryPainter.js";
import {TrackballCamera, registerCameraEvents} from "../../modules/Trackballcamera.js";
import V3 from "../../modules/V3.js";
import SolidColor from "../../materials/SolidColor.js";
import Diffuse from "../../materials/Diffuse.js";

/**
 * Iluminación de una superficie con un haz de luz.
 * @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 lightPosition = [2, 4, 0, 0];
    //Haz de luz
    let cylinder = new Cylinder(.52, 10, 30);
    let beamUniforms = { u_color: [1,1,0,.85], u_light_position: lightPosition};

    let beam = new GeometryPainter(gl, new Diffuse(gl, WebGL, cylinder, beamUniforms), M4.translate(0,-1,0));
    //Plano
    var rect = new RectangularPrism(10,2,4.5,true);
    let plane = new GeometryPainter(gl, new SolidColor(gl, WebGL, rect, [.65,.7,.7,1]), M4.translate(0,-1.7,0));    
    var fov = 80;
    
    let controls = document.getElementById("ui-container");
    controls.className = "right-box";
    var theta = 0;
    var slider = new Slider(controls, "θ", -180, 180, upadateAngle, theta, 1, ["#4994D0"]);

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

    let zNear = .1;
    let zFar = 200;
    let pos = new V3(0,-0.4,2.0);
    let camera = new TrackballCamera(pos);
    resize(canvas);

    gl.enable(gl.DEPTH_TEST);
    gl.enable(gl.CULL_FACE);
    //Transparecia
    gl.enable(gl.BLEND);
    gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
    gl.clearColor(0, 0, 0, 0);

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

    draw();


    function draw(){        
        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);
        var modelViewBeam = M4.multiply(viewMatrix, M4.rotateZ(theta));
        beamUniforms.u_light_position = lightPos;
        
        plane.draw(gl, viewMatrix, projectionMatrix);
        beam.draw(gl, modelViewBeam, projectionMatrix, beamUniforms);
    }
    function upadateAngle(value){
        theta = value;
        draw();
    }
    
}