import { Renderer2D } from './src/renderer';

import React from 'react';
import ReactDOM from 'react-dom';

import { MenuBar } from "./src/menu";
import { TriangleRenderer } from './src/triangle_renderer';

function findCanvas(){
    const canvas = document.querySelector("canvas");
    if(canvas === null){
        console.error("couldn't find canvas");
        throw new Error("canvas is null");
    }
    return canvas;
}

function getGLContext(canvas : HTMLCanvasElement){
    const gl = canvas.getContext("webgl2") as any as WebGL2RenderingContext|null;
    if(gl === null){
        console.error("webgl2 is not supported!");
        throw new Error("webgl2 not supported");
    }
    return gl;
}

function setupButton(){
    let toggle = false;
    const button = document.querySelector("#drawer-button") as HTMLDivElement;
    const drawer = document.querySelector("#drawer") as HTMLDivElement;
    button.addEventListener("click",()=>{
        toggle = !toggle;
        if(toggle){
            drawer.style.right = "0px";
        }
        else{
            drawer.style.right = "";
        }
    });
}

function main(){
    setupButton();
    const canvas = findCanvas();
    const gl = getGLContext(canvas);
    const renderer = new Renderer2D(gl);
    const trenderer = new TriangleRenderer(gl);
    renderer.prepare();
    trenderer.prepare(gl);

    ReactDOM.render(<MenuBar u={renderer.uniforms} 
        onUniformChange={(u)=>{renderer.settingUniform(u); renderer.draw(); 
            trenderer.draw(gl);
        }} />
        ,document.getElementById("drawer"));
    window.addEventListener("resize",(e)=>{
        e.preventDefault();
        canvas.width = document.body.clientWidth;
        canvas.height = document.body.clientHeight;
        renderer.draw();
        trenderer.draw(gl);
    });
    canvas.width = document.body.clientWidth;
    canvas.height = document.body.clientHeight;
    renderer.draw();
    trenderer.draw(gl);
}
main();