import { useEffect } from "react";
import { Meta3D, DracoCompression } from "../../plugins/meta3d";
import { useSearchParams } from "react-router-dom";

const id = "meta3d-container";
const dataUrl = "/meta3d/";
let meta3d: any;

const openData = async (dataId: string) => {
  const dataName = `data${dataId ? `-${dataId}` : ""}`;
  // DracoCompression.Configuration.decoder.wasmUrl =
  //   "/meta3d/js/draco_wasm_wrapper_gltf.js";
  // DracoCompression.Configuration.decoder.wasmBinaryUrl =
  //   "/meta3d/js/draco_decoder_gltf.wasm";
  // DracoCompression.Configuration.decoder.fallbackUrl =
  //   "/meta3d/js/draco_decoder_gltf.js";
  meta3d = new Meta3D(id);
  let data;
  await Promise.all([
    meta3d.init(),
    new Promise((resolve) => {
      const xhr = new XMLHttpRequest();
      xhr.open("GET", dataUrl + dataName, true);
      xhr.send();
      xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
          data = xhr.responseText;
          resolve(undefined);
        }
      };
    }),
  ]);
  meta3d.open({ data, running: true });
};

export default function Meta3d() {
  const [searchParams] = useSearchParams();
  const dataId = searchParams.get("id");

  useEffect(() => {
    openData(dataId || "");
    return () => {
      meta3d?.dispose();
    };
  }, []);

  return (
    <div
      id={id}
      style={{
        width: "100%",
        height: "100%",
      }}
    ></div>
  );
}
