"use strict";

import {resize, Color, Slider, hexToRgbNormalized} from "../../modules/HTMLUtils.js";
import WebGL from "../../modules/WebGLUtils.js";
import M4 from "../../modules/M4.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";
import SolidColor from "../../materials/SolidColor.js";

/**
 * Reflexión de color: Luz * Color.
 * @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.4);
    let colorUniform = {u_color: [0.2, 0.588, 1,1]};

    let figure = new GeometryPainter(gl, new SolidColor(gl, WebGL, cubeFigure), M4.multiply(M4.translate(0,.5,0), M4.rotateY(-35)));
    var fov = 90;
    if(window.innerWidth < window.innerHeight)
        fov = 120;

    let zNear = 1;
    let zFar = 100;
    var pos = new V3(0,1.6,2.3);
    let camera = new TrackballCamera(pos);
    
    var light_color = [1,1,1];
    var object_color = [0.121, 0.498, 0.121];
    var intensity;

    let controls = document.getElementById("ui-container");
    controls.className = "big-bottom-box";
    var light_pick_color = new Color(controls, "Luz", setLightColor, "#FFFFFF");
    var object_pick_color = new Color(controls, "Objeto", setObjectColor, "#1f7f1f");
    
    gl.enable(gl.DEPTH_TEST);
    gl.enable(gl.CULL_FACE); 

    window.addEventListener('resize', draw);
    registerCameraEvents(camera, canvas, draw);
    
    draw();
    
    function draw(){        
        resize(canvas);
        var {width, height} = gl.canvas;

        gl.clearColor(light_color[0], light_color[1], light_color[2], 1);
        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();
        
        intensity = [light_color[0] * object_color[0], light_color[1] * object_color[1], light_color[2] * object_color[2], 1.0];
        colorUniform.u_color = intensity;

        figure.draw(gl, viewMatrix, projectionMatrix, colorUniform);       
    }
    function setLightColor(value){
        light_color = value;
        draw();
    }
    function setObjectColor(value){
        object_color = value;
        draw();
    }
}