import react, { useState } from 'react';
import { useDispatch } from 'react-redux';

import { mapActions } from '../../store/map';


interface MouseHandlerProps {
  children: any;
}

const MouseHandler: react.FC<MouseHandlerProps> = (
  props: MouseHandlerProps
) => {
  const dispatch = useDispatch();

  const initialMouseState = {
    down: false,
    starting: { x: -1, y: -1 },
    timestamp: 0,
  };

  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)} (+${
          Date.now() - mouseState.timestamp
        }ms) `
      );
      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 },
      timestamp: Date.now(),
    });
  };

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

  const mouseMoveHandler = (event: any) => {
    event.preventDefault();
    if (mouseState.down && Date.now() - mouseState.timestamp > 50) {
      genericHandler(event);
      console.log(
        `dispatch ${JSON.stringify({
          x: event.pageX - mouseState.starting.x,
          y: event.pageY - mouseState.starting.y,
        })}`
      );
      dispatch(
        mapActions.shift({
          x: event.pageX - mouseState.starting.x,
          y: event.pageY - mouseState.starting.y,
        })
      );

      setMouseState({
        down: true,
        starting: {
          x: event.pageX,
          y: event.pageY,
        },
        timestamp: Date.now(),
      });
    }
  };

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

  const doubleClickHandler = (event: any) => {
    genericHandler(event);
    dispatch(
      mapActions.scale({
        factor: 2,
        center: { x: event.pageX, y: event.pageY },
      })
    );
  };

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

export default MouseHandler;
