import react, { useCallback, useState } from 'react';

import _ from 'lodash';

import { Transformation } from './viewport';

interface MouseHandlerProps {
  applyTransformations: (transformations: Transformation[]) => void;
  children: any;
}

const MouseHandler: react.FC<MouseHandlerProps> = (
  props: MouseHandlerProps
) => {
  const initialMouseState = {
    down: false,
    starting: { x: -1, y: -1 },
  };

  const [mouseState, setMouseState] = useState(initialMouseState);

  console.log('MouseHandler, mouseState: ' + JSON.stringify(mouseState));

  const genericHandler = (event: any) => {
    console.log('Log - Event: ' + event.type);
    if (event.pageX !== undefined) {
      console.log(`Mouse : ${event.pageX}, ${event.pageY}`);
      console.log('mouseState: ' + JSON.stringify(mouseState));
      return;
    }
  };

  const mouseLeaveHandler = (event: any) => {
    genericHandler(event);
    throtteledMouseMoveHandler.cancel();
    setMouseState(initialMouseState);
  };

  const mouseDownHandler = (event: any) => {
    event.preventDefault();
    genericHandler(event);
    setMouseState({
      down: true,
      starting: { x: event.pageX, y: event.pageY },
    });
  };

  const mouseUpHandler = (event: any) => {
    genericHandler(event);
    event.preventDefault();
    setMouseState(initialMouseState);
  };

  const mouseMoveHandler = (event: any) => {
    event.preventDefault();
    if (mouseState.down) {
      genericHandler(event);
      props.applyTransformations([
        {
          translate: {
            x: event.pageX - mouseState.starting.x,
            y: event.pageY - mouseState.starting.y,
          },
        },
      ]);
      setMouseState({
        down: true,
        starting: {
          x: event.pageX,
          y: event.pageY,
        },
      });
    }
  };

  const throtteledMouseMoveHandler = useCallback(
    _.throttle(mouseMoveHandler, 50),
    [mouseState.down]
  );

  const doubleClickHandler = (event: any) => {
    genericHandler(event);
    props.applyTransformations([
      {
        scale: {
          factor: 2,
          center: { x: event.pageX, y: event.pageY },
        },
      },
    ]);
  };

  return (
    <div
      className='viewport mouse-handler'
      onMouseDown={mouseDownHandler}
      onMouseMove={throtteledMouseMoveHandler}
      onMouseUp={mouseUpHandler}
      onMouseLeave={mouseLeaveHandler}
      onDoubleClick={doubleClickHandler}
    >
      {props.children}
    </div>
  );
};

export default MouseHandler;
