import { useEffect, useState } from 'react';
import { usePinch } from 'react-use-gesture';

const useGestureScale = (
  domTarget: RefObject<HTMLDivElement> | null,
): [number] => {
  const [zoom, set] = useState(0);

  const bind = usePinch(
    ({ offset: [d] }) => {
      set(d / 200);
    },
    {
      domTarget,
      eventOptions: { passive: false },
      distanceBounds: { min: -100, max: 150 },
    },
  );

  const notAllowOriginalEvent = (e: Event) => e.preventDefault();

  useEffect(() => {
    document.addEventListener('gesturestart', notAllowOriginalEvent);
    document.addEventListener('gesturechange', notAllowOriginalEvent);

    return () => {
      document.removeEventListener('gesturestart', notAllowOriginalEvent);
      document.removeEventListener('gesturechange', notAllowOriginalEvent);
    };
  }, []);

  useEffect(() => {
    bind();
  }, [bind]);

  return [zoom];
};

export default useGestureScale;
