import * as React from 'react';
import { ReactSVGPanZoom, Tool, TOOL_PAN, Value } from 'react-svg-pan-zoom';
import { Container } from './Elements/Container';
import { IContainerModel } from '../../Interfaces/IContainerModel';
import { Selector } from './Elements/Selector/Selector';
import { DepthDimensionLayer } from './Elements/DepthDimensionLayer';
import { MAX_FRAMERATE, SHOW_DIMENSIONS_PER_DEPTH } from '../../utils/default';
import { SymbolLayer } from './Elements/SymbolLayer';
import { ISymbolModel } from '../../Interfaces/ISymbolModel';
import { DimensionLayer } from './Elements/DimensionLayer';

interface ISVGProps {
  className?: string
  viewerWidth: number
  viewerHeight: number
  width: number
  height: number
  containers: Map<string, IContainerModel>
  children: IContainerModel
  selected?: IContainerModel
  symbols: Map<string, ISymbolModel>
  selectContainer: (containerId: string) => void
}

export const ID = 'svg';

export function SVG(props: ISVGProps): JSX.Element {
  const [tool, setTool] = React.useState<Tool>(TOOL_PAN);
  const [value, setValue] = React.useState<Value>({} as Value);
  const [scale, setScale] = React.useState<number>(value.a ?? 1);

  const svgViewer = React.useRef<ReactSVGPanZoom>(null);

  // Framerate limiter
  const delta = React.useRef(0);
  const timer = React.useRef(performance.now());
  const renderCounter = React.useRef(0);
  // Debug: FPS counter
  // const startTimer = React.useRef(Date.now());
  // console.log(renderCounter.current / ((Date.now() - startTimer.current) / 1000));

  UseFitOnce(svgViewer, props.width, props.height);

  const xmlns = '<http://www.w3.org/2000/svg>';
  const properties = {
    width: props.width,
    height: props.height,
    xmlns
  };

  let children: React.ReactNode | React.ReactNode[] = [];
  children = <Container
    key={`container-${props.children.properties.id}`}
    containers={props.containers}
    model={props.children}
    depth={0}
    scale={scale}
    selectContainer={props.selectContainer}
  />;

  return (
    <div id={ID} className={props.className}>
      <ReactSVGPanZoom
        ref={svgViewer}
        width={props.viewerWidth}
        height={props.viewerHeight}
        tool={tool} onChangeTool={setTool}
        value={value} onChangeValue={(value: Value) => {
          // Framerate limiter
          const newTimer = performance.now();
          delta.current += (newTimer - timer.current) / 1000;
          timer.current = newTimer;
          if (delta.current <= (1 / MAX_FRAMERATE)) {
            return;
          }

          renderCounter.current = renderCounter.current + 1;
          delta.current = delta.current % (1 / MAX_FRAMERATE);
          setValue(value);
        }}
        onZoom={(event: unknown) => {
          const value = event as Value;
          setScale(value.a);
        }}
        background={'#ffffff'}
        defaultTool='pan'
        miniatureProps={{
          position: 'left',
          background: '#616264',
          width: 120,
          height: 120
        }}
      >
        <svg {...properties}>
          {children}
          {SHOW_DIMENSIONS_PER_DEPTH
            ? <DepthDimensionLayer containers={props.containers} scale={scale} roots={props.children} />
            : null}
          <DimensionLayer containers={props.containers} scale={scale} root={props.children} />
          <SymbolLayer scale={scale} symbols={props.symbols} />
          <Selector containers={props.containers} scale={scale} selected={props.selected} /> {/* leave this at the end so it can be removed during the svg export */}
        </svg>
      </ReactSVGPanZoom>
    </div>
  );
}

function UseFitOnce(svgViewer: React.RefObject<ReactSVGPanZoom>, width: number, height: number): void {
  React.useEffect(() => {
    svgViewer?.current?.fitToViewer();
  }, [svgViewer, width, height]);
}
