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

import _ from 'lodash';

import Background from './background';

import '../theme/viewport.css';

const Viewport: react.FC<{}> = (props: {}) => {
  console.log('rendering viewport');
  const [shift, setShift] = useState({ x: 1000, y: 1000 });

  const initialMouseState = {
    down: false,
    starting: { x: -1, y: -1 },
  };
  const [mouseState, setMouseState] = useState(initialMouseState);

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

  const genericHandler = (event: any) => {
    console.log('Log - Event: ' + event.type);
  };

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

  const mouseUpHandler = (event: any) => {
    event.preventDefault();
    console.log('Log - Up, now do something ! ');
    setMouseState(initialMouseState);
    genericHandler(event);
  };

  const mouseMoveHandler = (event: any) => {
    event.preventDefault();
    if (mouseState.down) {
      console.log('Log - Moving...' + event.pageX);
      genericHandler(event);
      setShift((shift) => ({
        x: shift.x + (mouseState.starting.x - event.pageX),
        y: shift.y + (mouseState.starting.y - event.pageY),
      }));
      setMouseState((mouseState) => ({
        down: true,
        starting: {
          x: event.pageX,
          y: event.pageY,
        },
      }));
    }
  };

  const throtteledMouseMoveHandler = useMemo(
    () => _.throttle(mouseMoveHandler, 100),
    undefined
  );

  return (
    <div
      className='viewport'
      onMouseDown={mouseDownHandler}
      onMouseMove={throtteledMouseMoveHandler}
      onMouseUp={mouseUpHandler}
    >
      <Background shift={shift} />
    </div>
  );
};

export default Viewport;
