import react, { useState } from 'react';

interface Point {
  x: number;
  y: number;
}

interface SingleTouchHandlerProps {
  boardSize: number;
  shift: Point;
  addShift: (shift: Point) => void;
  zoom: number;
  addZoom: (zoomFactor: number, center: Point) => void;
  children?: any;
}

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

  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);
    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 },
        timestamp: Date.now(),
      });
    }
  };

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

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

  return (
    <div
      className='handler'
      onTouchStart={touchStartHandler}
      onTouchMove={touchMoveHandler}
      onTouchEnd={touchEndHandler}
      onTouchCancel={touchCancelHandler}
    >
      {props.children === undefined ? <></> : props.children}
    </div>
  );
};

export default SingleTouchHandler;
