import { Drawer2D } from './src/drawer2D';

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

import { MenuBar } from "./src/menu";
import { TriangleDrawer } from './src/triangle_drawer';
import {CanvasApp} from "./src/app"

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 app = new CanvasApp(gl);
    if(!app.intialize()){
        console.log("app initialize failed!!!");
        return;
    }
    ReactDOM.render(<MenuBar u={app.getDefaultUniform()} 
        onUniformChange={(u)=>{app.onChangeUniform(u);
        }} />
        ,document.getElementById("drawer"));
    window.addEventListener("resize",(e)=>{
        e.preventDefault();
        canvas.width = document.body.clientWidth;
        canvas.height = document.body.clientHeight;
    });
    canvas.width = document.body.clientWidth;
    canvas.height = document.body.clientHeight;
    app.startRun();
    app.startDraw();
}
main();