import { LightClusterVolumeMaterial } from "./LightClusterVolumeMaterial.js";
import { AxesHelper, BoxBufferGeometry, Mesh, MeshBasicMaterial, PerspectiveCamera, Scene, WebGLRenderer } from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";

/**
 *
 * @param {LightManager} lm
 * @param {Camera} camera
 * @returns {{mesh:Mesh, update:function}}
 */
export function buildLightClusterWidget(lm, camera) {
    const m = new LightClusterVolumeMaterial(lm.getTextureClusters());
    m.depthTest = true;
    m.depthWrite = true;

    const geometry = new BoxBufferGeometry();

    const mesh = new Mesh(geometry, m);


    const group = new Scene();

    group.add(mesh);

    group.add(new Mesh(geometry, new MeshBasicMaterial({
        wireframe: true,
        color: '#FFFFFF',
        depthTest: true
    })));

    const axesHelper = new AxesHelper();

    axesHelper.position.set(-0.5, -0.5, -0.5);
    group.add(axesHelper);


    const renderer = new WebGLRenderer({
        antialias: true,
        alpha: true
    });

    renderer.autoClear = true;
    renderer.setClearAlpha(0);

    const render_cam = new PerspectiveCamera(45, 1, 0.1, 10);

    render_cam.position.set(1, 1, -3);
    render_cam.lookAt(0, 0, 0);

    renderer.setSize(256, 256);

    const controls = new OrbitControls(render_cam, renderer.domElement);

    return {
        domElement: renderer.domElement,
        update() {
            render_cam.updateProjectionMatrix();
            const t = lm.getTextureClusters().clone();
            t.needsUpdate = true;
            m.uniforms.map.value = t;
            m.uniforms.cameraPos.value.copy(render_cam.position)

            renderer.render(group, render_cam);

        }
    };
}
