import { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { UILayer } from "~ui/UI";
import { addLayer, removeLayer, showLayer, hideLayer } from "~store/ui/reducer";

export default function useUILayer(data: UILayer, show: boolean) {
  const dispatch = useDispatch();
  const id = data.type + "-" + Math.random().toString(32).slice(2);

  const [visible, setVisible] = useState(show);

  useEffect(() => {
    dispatch(addLayer({ id, data }));
    return () => {
      dispatch(removeLayer({ id }));
    };
  }, []);

  useEffect(() => {
    if (visible) {
      dispatch(showLayer({ id }));
    } else {
      dispatch(hideLayer({ id }));
    }
  }, [visible]);

  if (show != visible) {
    setVisible(show);
  }

  return id;
}
