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

import _ from 'lodash';

import { Point } from './viewport';

interface MouseHandlerProps {
  updateShift: (shiftDelta: Point) => 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.type.startsWith('mouse')) {
      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) => {
    genericHandler(event);
    event.preventDefault();
    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.updateShift({
        x: mouseState.starting.x - event.pageX,
        y: mouseState.starting.y - event.pageY,
      });
      setMouseState({
        down: true,
        starting: {
          x: event.pageX,
          y: event.pageY,
        },
      });
    }
  };

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

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

export default MouseHandler;
