import { useState, useEffect } from 'react';
import useZoomTransform from '../../../hooks/useZoomTransform';

/**
 * Hook to compute a clipping mask to keep label leader lines from intersecting
 * with the labels themselves in a way that looks bad.
 */
const useMask = function useMask({
  clippingRef,
  start
}) {
  const [clippingRect, setClippingRect] = useState();
  const {
    zoomLevel
  } = useZoomTransform();
  useEffect(() => {
    if (!clippingRef || !clippingRef.current) {
      return setClippingRect({
        x: 0,
        y: 0,
        width: 0,
        height: 0
      });
    }
    const {
      width: w,
      height: h
    } = clippingRef.current.getBoundingClientRect();
    const width = w * (1 - zoomLevel);
    const height = h * (1 - zoomLevel) - 8;
    const x = start[0] - width / 2;
    const y = start[1] - height / 2 - 2;
    return setClippingRect(oldRect => {
      const newRect = {
        x,
        y,
        width,
        height
      };
      if (!oldRect) return newRect;
      const hasNewValue = Object.entries(oldRect).some(([key, oldVal]) => oldVal !== newRect[key]);
      return hasNewValue ? newRect : oldRect;
    });
  });
  return clippingRect;
};
export default useMask;