import react, { useState } from 'react';
import { throttle } from 'lodash';
import { Point } from './types';
import { handlersConfig } from './config';

export interface HandlersProperties {
  /**Transform the map:
   * * Shift the map by a number of pixel
   * * Multiply the zoom by deltaZoom around the zoomCenter
   *   */
  transformMap: (
    deltaShift: Point | null,
    deltaZoom: number | null,
    zoomCenter: Point | null
  ) => void;
}
/**
 *
 * @param props
 * @returns A div with handlers
 */
export const Handlers: react.FC<HandlersProperties> = (
  props: HandlersProperties
) => {
  const genericHandler = (event: any) => {
    // console.log(`Log - Event:  ${event.type}`);
    // if (event.clientX !== undefined) {
    //   console.log(
    //     `Mouse : ${event.clientX}, ${event.clientY}, target: ${event.target}`
    //   );
    //   console.log(
    //     `mouseState: ' ${JSON.stringify(mouseState)} (+${
    //       Date.now() - mouseState.timestamp
    //     }ms) `
    //   );
    //   return;
    //}
  };

  const initialMouseState = {
    down: false,
    starting: { x: -1, y: -1 },
  };
  const mouseLeaveHandler = (event: any) => {
    genericHandler(event);
    setMouseState(initialMouseState);
  };

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

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

  const mouseMoveHandler = throttle((event: any) => {
    genericHandler(event);
    if (mouseState.down) {
      props.transformMap(
        {
          x: event.clientX - mouseState.starting.x,
          y: event.clientY - mouseState.starting.y,
        },
        null,
        null
      );
      setMouseState({
        down: true,
        starting: {
          x: event.clientX,
          y: event.clientY,
        },
      });
    }
  }, handlersConfig.mouseMoveThrottleDelay);

  const [mouseState, setMouseState] = useState(initialMouseState);
  return (
    <div
      className='handler'
      role='presentation'
      onMouseDown={mouseDownHandler}
      onMouseMove={mouseMoveHandler}
      onMouseUp={mouseUpHandler}
      onMouseLeave={mouseLeaveHandler}
    />
  );
};

export default Handlers;
