import { Sampler2D } from "./texture/sampler/Sampler2D.js";
import { renderObjectToSampler2D } from "./util/renderObjectToSampler2D.js";

/**
 *
 * @param {{create:function():Object3D}} asset
 * @param {Vector2} size
 * @param {WebGLRenderer|undefined} [renderer]
 * @param {AABB2} focus
 * @returns {{domElement: HTMLCanvasElement, pixels: Uint8Array, graphics, camera: PerspectiveCamera, render: Function, dispose:Function, mesh, scene: Scene}}
 */
export function makeModelView(asset, size, renderer, focus) {
    const mesh = asset.create();

    const canvas = document.createElement("canvas");

    // init renderer TODO can be deferred
    canvas.width = size.x;
    canvas.height = size.y;


    const canvas_ctx_2d = canvas.getContext("2d");
    const imageData = canvas_ctx_2d.createImageData(size.x, size.y);

    const sampler = new Sampler2D(imageData.data, 4, size.x, size.y);

    const proxy_renderer = renderObjectToSampler2D(sampler, mesh, renderer, focus);

    function render() {

        proxy_renderer.render();

        canvas_ctx_2d.clearRect(0, 0, canvas.width, canvas.height);
        canvas_ctx_2d.putImageData(imageData, 0, 0);
    }


    return {
        mesh: mesh,
        camera: proxy_renderer.camera,
        scene: proxy_renderer.scene,
        graphics: renderer,
        render,
        domElement: canvas,
        dispose: proxy_renderer.dispose
    };
}
