import { DataProvider } from '@h5web/app';
import type { DataProviderApi } from '@h5web/app/src/providers/api';
import type { ReactNode } from 'react';
import { useEffect, useMemo } from 'react';

import { H5WasmApi } from './h5wasm-api';

interface Props {
  filename: string[];
  fileExt:string[];
  buffer: ArrayBuffer;
  getExportURL?: DataProviderApi['getExportURL'];
  children: ReactNode;
}

function H5WasmProvider(props: Props) {
  const { filename,fileExt, buffer, getExportURL, children } = props;

  const api = useMemo(
    () => new H5WasmApi(filename,fileExt, buffer, getExportURL),
    [filename,fileExt, buffer, getExportURL]
  );

  useEffect(() => {
    return () => void api.cleanUp();
  }, [api]);

  return <DataProvider api={api}>{children}</DataProvider>;
}

export default H5WasmProvider;
