import { useEffect, useState } from 'react';
/**
 *
 * @param areaId
 * @param onDragStart
 * @param onDrag
 * @param onDragEnd
 * @returns onStart function to be used in onMouseDown event
 */
export function useDraggableArea({
  areaId,
  onDragStart = () => {},
  onDrag,
  onDragEnd = () => {}
}) {
  const [isDragging, setIsDragging] = useState(false);
  const onStart = e => {
    const draggableEvent = Object.assign(e, {
      areaId
    });
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(true);
    onDragStart(draggableEvent);
  };
  useEffect(() => {
    if (!isDragging) {
      return;
    }
    function onDragHandler(e) {
      const draggableEvent = Object.assign(e, {
        areaId
      });
      e.preventDefault();
      e.stopPropagation();
      onDrag(draggableEvent);
    }
    function onDragEndHandler(e) {
      const draggableEvent = Object.assign(e, {
        areaId
      });
      e.preventDefault();
      e.stopPropagation();
      removeListeners();
      setIsDragging(false);
      onDragEnd(draggableEvent);
    }
    function onDragBlurHandler() {
      setIsDragging(false);
      onDragEnd(areaId);
      removeListeners();
    }
    window.addEventListener('mousemove', onDragHandler);
    window.addEventListener('mouseup', onDragEndHandler);
    window.addEventListener('blur', onDragBlurHandler);
    function removeListeners() {
      window.removeEventListener('mousemove', onDragHandler);
      window.removeEventListener('mouseup', onDragEndHandler);
      window.removeEventListener('blur', onDragBlurHandler);
    }
    return removeListeners;
  }, [isDragging, onDragStart, onDrag, onDragEnd, areaId]);
  return onStart;
}