"use strict";

import {resize, resizeAndCenterX, Slider, TextBox} 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 GeometryPainter from "../../geometry/GeometryPainter.js";
import SolidColor from "../../materials/SolidColor.js";
import M3 from "../../modules/M3.js";
import V3 from "../../modules/V3.js";

/**
 * Función de correspondencia:
 * Transformaciones sobre las coordenadas de textura. 
 * @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/fave.png";
    let material =  new Texture(gl, WebGL, planeFigure, srcTexture, setTexture, true, {wrap_s : gl.REPEAT, wrap_t : gl.REPEAT}); 
    planeFigure.setTexcoords( [-1,-1, 2,-1, 2,2, -1,2]);
    let textureMaterial =  new Texture(gl, WebGL, planeFigure, srcTexture, setTexture, true, {wrap_s : gl.REPEAT, wrap_t : gl.REPEAT}); 
   
    let frameMaterial = new SolidColor(gl, WebGL, new Square(.32), [0.6,0.8,0.196,.45]);
    let newCenter = new V3(.1,.115,0);
    let texturePlane = new GeometryPainter(gl, textureMaterial, M4.translate(newCenter.x+.06, newCenter.y+0.045, .026));
    let projectivePlane = new GeometryPainter(gl, material, M4.multiply(M4.translate(0,0,-.5), M4.scale(.5,.5,.5)));
    let frame = new GeometryPainter(gl, frameMaterial);
    var viewMatrix = M4.camera(new V3(newCenter.x,newCenter.y,.55), newCenter, new V3(0,1,0));
    let uniforms = {};
    let loadedTexture;
    let controls = document.getElementById("ui-container-center");
    controls.className = "big-bottom-box";

    //let textureLabel = new TextBox(container, {top:1, left:17.5}, "Espacio de textura");
    //let planeLabel = new TextBox(container, {top:1, right:9.5}, "Plano renderizado");

    var translation = [0,0];
    var scale = [1,1];
    var phi = 0;
    let sliders = [ new Slider(controls, "T<sub>u</sub>", -.5,.5, updateTranslation(0), translation[0], .1, ["#4994D0"]),
                    new Slider(controls, "T<sub>v</sub>", -.5,.5, updateTranslation(1), translation[1], .1, ["#4994D0"]),
                    new Slider(controls, "R<sub>φ</sub>", 0, 360, updateRotation, phi, 1, ["#4994D0"]),
                    new Slider(controls, "S<sub>u</sub>", 0.1,2, updateScale(0), scale[0], 0.1, ["#4994D0"]),
                    new Slider(controls, "S<sub>v</sub>", 0.1,2, updateScale(1), scale[1], 0.1, ["#4994D0"])];

    gl.enable(gl.DEPTH_TEST);
    gl.enable(gl.SCISSOR_TEST);
    //Transparecia
    gl.enable(gl.BLEND);
    gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);

    gl.clearColor(0, 0, 0, 0);
    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);

    window.addEventListener('resize', draw);
    
    draw();

    function draw(){        

        resizeAndCenterX(controls, {bottom: 0});
        resize(canvas);
        var {width, height} = gl.canvas;
       
        const leftWidth = width * .5| 0;
        const startWidth = width * .02;
        const leftHeight = height - leftWidth ;
        const rightWidth = width-leftWidth;
        
        var projectionMatrix = M4.perspective(95, 1, .1, 100);
        var lw = leftWidth-startWidth;
         //Izquierda
        gl.viewport(startWidth, leftHeight, lw, lw);
        gl.scissor(startWidth, leftHeight, lw, lw);
        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
         
        if(loadedTexture){
            uniforms.u_texture = {id:0, texture: loadedTexture};
            uniforms.u_texture_matrix =  M3.identity();
            texturePlane.drawSimple(gl, viewMatrix, projectionMatrix, uniforms);
        } 
        var modelFrameMatrix = M4.multiplyArray([M4.translate(translation[0]*.3, translation[1]*.3,0),
                                                M4.rotateZ(phi), M4.scale(scale[0], scale[1],1)]);
        frame.drawSimple(gl, M4.multiply(viewMatrix, modelFrameMatrix), projectionMatrix);
        //Derecha
        gl.viewport(startWidth+leftWidth, leftHeight, rightWidth, rightWidth);
        gl.scissor(startWidth+leftWidth, leftHeight, rightWidth, rightWidth);
        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
        modelFrameMatrix = M3.multiply( M3.translate(translation[0], translation[1]), 
                                        M3.multiply(M3.rotate(phi), M3.scale(scale[0], scale[1])));
         if(loadedTexture){    
            uniforms.u_texture = {id:0, texture: loadedTexture};
            uniforms.u_texture_matrix =  modelFrameMatrix;
            projectivePlane.drawSimple(gl, M4.identity(), projectionMatrix, uniforms);
        }     
    }
    function setTexture(texture){
        loadedTexture = texture;
        draw();
    }
    function updateScale(index){
        return function(value){
            scale[index] = value;
            draw();
        };
    }
    function updateRotation(value){
        phi = value;
        draw();
    }
    function updateTranslation(index){
        return function(value){
            translation[index] = value;
            draw();
        };
    }
} 
function Square(w=1){
    this.width = w;
    this.byIndices = false;
}
Square.prototype.getVertices = function(){
    let size = this.width;
    return [ 0, 0, 0.051, 
             1*size, 0, 0.051,
             1*size, 1*size, 0.051,
             0, 1*size, 0.051
        ];
}
Square.prototype.getFaces = function(){
    return [ 0, 1, 2,
             0, 2, 3];
}