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

import _ from 'lodash';

import { Point } from './viewport';

interface SingleTouchHandlerProps {
  updateShift: (shiftDelta: Point) => void;
  children: any;
}

const SingleTouchHandler: react.FC<SingleTouchHandlerProps> = (
  props: SingleTouchHandlerProps
) => {
  const initialTouchState = {
    state: 'up',
    touch: { x: -1, y: -1 },
  };

  const [touchState, setTouchState] = useState(initialTouchState);

  console.log('SingleTouchHandler, touchState: ' + JSON.stringify(touchState));

  const genericHandler = (event: any) => {
    console.log('Log - Event: ' + event.type);
    if (event.type.startsWith('touch')) {
      if (event.touches.length > 0) {
        console.log(
          `Touch1 : (${event.touches[0].pageX}, ${event.touches[0].pageY})`
        );
      }
      console.log('touchState: ' + JSON.stringify(touchState));
      return;
    }
  };

  const touchCancelHandler = (event: any) => {
    genericHandler(event);
    throtteledTouchMoveHandler.cancel();
    setTouchState(initialTouchState);
  };

  const touchStartHandler = (event: any) => {
    genericHandler(event);
    //    event.preventDefault();
    if (event.touches.length === 1) {
      setTouchState({
        state: 'pointer',
        touch: { x: event.touches[0].pageX, y: event.touches[0].pageY },
      });
    }
  };

  const touchEndHandler = (event: any) => {
    genericHandler(event);
    //  event.preventDefault();
    setTouchState(initialTouchState);
    throtteledTouchMoveHandler.cancel();
  };

  const touchMoveHandler = (event: any) => {
    //  event.preventDefault();
    if (touchState.state === 'pointer') {
      if (event.touches.length === 1) {
        genericHandler(event);
        props.updateShift({
          x: touchState.touch.x - event.touches[0].pageX,
          y: touchState.touch.y - event.touches[0].pageY,
        });
        setTouchState({
          state: 'pointer',
          touch: {
            x: event.touches[0].pageX,
            y: event.touches[0].pageY,
          },
        });
      }
    }
  };

  const throtteledTouchMoveHandler = useCallback(
    _.throttle(touchMoveHandler, 100),
    [touchState.state]
  );

  return (
    <div
      className='viewport'
      onTouchStart={touchStartHandler}
      onTouchMove={throtteledTouchMoveHandler}
      onTouchEnd={touchEndHandler}
      onTouchCancel={touchCancelHandler}
    >
      {props.children}
    </div>
  );
};

export default SingleTouchHandler;
