import _ from 'lodash';
import React, { useRef, useEffect, useCallback } from 'react';
import {
  initScene,
  cleanup,
  createScene,
  engine,
  scene,
  warningChecks,
  updateItem,
  getGLTFData,
  takePreviewScreenshots,
} from './helpers';
import { CanvasContainer, RenderCanvas } from './styles';

export let reactProps;

const Canvas = props => {
  const { file, guidURL, reinitialize, updateData, exportModel, toDownload, exportType } = props;
  const canvasRef = useRef();
  const checkForWarnings = useCallback(() => {
    if (scene) {
      const hasPlugin = scene?.loadingPluginName;
      if (hasPlugin) warningChecks();
    }
  }, []);

  useEffect(() => {
    return () => {
      cleanup();
    };
  }, []);

  useEffect(() => {
    initScene({ canvasRef });
  }, [ canvasRef, guidURL ]);

  useEffect(() => {
    reactProps = props;
  }, [ props ]);

  useEffect(() => {
    const createNewScene = true;

    if ((file) || (guidURL && engine)) createScene();
    if (!file && !guidURL && scene) createScene(createNewScene);
  }, [ file, guidURL ]);

  useEffect(() => {
    checkForWarnings();
  }, [ checkForWarnings ]);

  useEffect(() => {
    if (scene && !_.isEmpty(updateData)) {
      updateItem(updateData);
    }
  }, [ updateData ]);

  useEffect(() => {
    if (canvasRef && reinitialize) {
      cleanup();
      initScene({ canvasRef });
    }
  }, [ canvasRef, reinitialize ]);

  useEffect(() => {
    if (exportModel && exportType) {
      getGLTFData(exportType, toDownload);
      takePreviewScreenshots();
    }
  }, [ exportModel, exportType, toDownload ]);

  return (
    <CanvasContainer {...props}>
      <RenderCanvas ref={canvasRef} />
    </CanvasContainer>
  );
};

export default Canvas;