import * as MU from "../../../modules/MathUtils.js";
import * as Utils from "../../../modules/HTMLUtils.js";
import WebGL from "../../../modules/WebGLUtils.js";
import M3 from "../../../modules/M3.js";
import V2 from "../../../modules/V2.js";
import Grid from "../../../geometry/Grid.js";
import Vector2D from "../../../geometry/Vector2D.js";

/**
 * Vectores equivalentes.
 * @author Melissa Méndez Servín.
 */
window.addEventListener("load", main);

function main(){
    document.body.className = "background_0";
    var canvas = document.getElementById("gl_canvas");
    var gl = WebGL.init(canvas);
    if(!gl) return;

    const unit = 25;    
    Utils.resize(canvas);
    //Grid
    var grid = new Grid(gl, unit, false);
    //Vectores
    const numVectors = 8;
    let vectors = [];
    let uniqueVector = new V2(3,2);
    for(var i = 0; i < numVectors + 1; i++){
        var color = i == 0 ? [76, 81, 109 , 255] : [93, 118, 169, 255];
        vectors[i] = [ new Vector2D(gl, WebGL, new V2(-1,0), uniqueVector, unit, 4, color),
                       uniqueVector] ;
    }
    var time = 0; //Contador de tiempo para hacer la espera
    
    window.addEventListener('resize', draw);
    requestAnimationFrame(draw);

    function draw(){
        Utils.resize(canvas);
        
        const {width, height} = gl.canvas;
        gl.viewport(0, 0, width, height);
        gl.clearColor(0, 0, 0, 0);
        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER);

        //Grid
        grid.draw(gl);
        var projectionMatrix = M3.projection(-width/2, width/2, height/2, -height/2);
        
        //Flechas
        if(time == 0){
            changevectorsPositions(width, height);
        }
        
        for(var i= 1; i < numVectors + 1; i++){
            vectors[i][0].draw(gl, projectionMatrix, null, null, vectors[i][1]);
        }
        vectors[0][0].draw(gl, projectionMatrix);
        
        time = (time + 1) % 100;
        requestAnimationFrame(draw);
    }
    /**
     * Actualiza la matriz de modelo, cambiando posición de los vectores 
     * equivalentes.
     * @param {*} width el ancho del canvas
     * @param {*} height el alto del canvas
     */
    function changevectorsPositions(width, height){
        const maxX = (.5 * width)/unit;
        const maxY = (.5 * height)/unit;
        var tx,ty;
        for(var i = 1; i < numVectors + 1; i++){
            if(i <= 2){ //Cuadrante IzqSup
                tx = MU.randomIntR(-maxX, 0);
                ty = MU.randomIntR(0, maxY);
            }else if(i <= 4){ //Cuadrante DerSup
                tx = MU.randomIntR(0, maxX);
                ty = MU.randomIntR(0, maxY);
            }else if(i <= 6){ //Cuadrante IzqInf
                tx = MU.randomIntR(-maxX, 0);
                ty = MU.randomIntR(-maxY, 0);
            }else{ //Cuadrante DerInf
                tx = MU.randomIntR(0, maxX);
                ty = MU.randomIntR(-maxY, 0);
            }
            vectors[i][1] = new V2(tx,ty);
        }
    }

}