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

import _ from 'lodash';

import MouseHandler from './mouse-handler';
import Layer from './layer';

import '../theme/viewport.css';
import SingleTouchHandler from './single-touch-handler';
import DoubleTouchHandler from './double-touch-handler';

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

interface ViewportProps {
  children: any;
}

const Viewport: react.FC<ViewportProps> = (props: ViewportProps) => {
  //console.log(`--- Rendering viewport, props: ${JSON.stringify(props)} ---`);

  const initialShitf: Point = { x: 0, y: 0 };

  const [shift, setShift] = useState(initialShitf);

  const [zoom, setZoom] = useState(1);

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

  // TODO: implement resize event
  // TODO: check boundaries

  const updateShift = (shiftDelta: Point) => {
    setShift({ x: shift.x + shiftDelta.x, y: shift.y + shiftDelta.y });
  };

  const updateZoom = (zoomFactor: number, center: Point) => {
    const newZoom = zoom * zoomFactor;
    setZoom(newZoom);
    setShift({
      x: shift.x + center.x / zoom - center.x / newZoom,
      y: shift.y + center.y / zoom - center.y / newZoom,
    });
    //   setShift({
    //     x: shift.x + 1440 / 2 / zoom - window.innerWidth / 2 / newZoom,
    //     y: shift.y + 2904 / 2 / zoom - window.innerHeight / 2 / newZoom,
    //   });
  };

  return (
    <div className='viewport'>
      <MouseHandler updateShift={updateShift}>
        <SingleTouchHandler updateShift={updateShift}>
          <DoubleTouchHandler updateZoom={updateZoom}>
            <Layer shift={shift} zoom={zoom}>
              {props.children}
            </Layer>
          </DoubleTouchHandler>
        </SingleTouchHandler>
      </MouseHandler>
    </div>
  );
};

export default Viewport;
