import { useEffect, useRef, useState, useImperativeHandle, forwardRef } from 'react';
import { renderSchematic } from '@enginehub/schematicwebviewer';
import { Buffer } from 'buffer';
window.Buffer = Buffer;

export const Render = forwardRef(({schemUrl}, ref) => {
    const canvasRef = useRef(null);
    const jarUrl = '/1.21.4.jar';
    const getEngineRef = useRef(() => {});

    useImperativeHandle(ref, () => ({
        getEngine: () => getEngineRef.current()
    }));

    const alreadyLoaded = useRef(false);
    useEffect(() => {
        if (alreadyLoaded.current) {
            return;
        }
        alreadyLoaded.current = true;
        const loadAndRenderSchematic = async () => {
            try {
                const response = await fetch(schemUrl);
                const blob = await response.blob();

                const reader = new FileReader();
                reader.onloadend = async () => {
                    const base64 = reader.result.split(',')[1];

                    if (canvasRef.current) {
                        const { getEngine: getEngine } = await renderSchematic(canvasRef.current, base64, {
                            getClientJarUrl: async () => jarUrl,
                            renderBars: false,
                            renderArrow: false,
                            orbitSpeed: 0.01
                        });
                        getEngineRef.current = getEngine;
                    }
                };

                reader.readAsDataURL(blob);
            } catch (e) {
                console.error(e);
            }
        };

        loadAndRenderSchematic();
        return () => {
            const engine = getEngineRef.current();
            if (engine) {
                engine.stopRenderLoop();
                engine.dispose();
            }
        };
    }, [schemUrl]);

    return <canvas ref={canvasRef} id="schematicRenderer" style={{height: "100%", width: "100%"}} />;
})
