import { useRef, useState, useEffect } from 'react';
import useCallAd from './useCallAd';
const useMountOnObserved = function useMountOnObserved({
  observationThreshold,
  rootMargin,
  rootThreshold = 1,
  rootNode,
  id,
  type
}) {
  const self = useRef();
  const [observed, setObserved] = useState(false);
  const [callAd, mounted] = useCallAd({
    id,
    type
  });
  useEffect(() => {
    if (!observed) {
      const options = {
        root: rootNode || null,
        rootMargin,
        threshold: rootThreshold
      };
      let tm;
      const cb = entries => {
        const entry = entries[0];
        if (entry.isIntersecting) {
          tm = setTimeout(() => {
            callAd();
            setObserved(true);
          }, observationThreshold);
        }
        if (!entry.isIntersecting && !!tm) {
          clearTimeout(tm);
        }
      };
      const observer = new window.IntersectionObserver(cb, options);
      if (self.current) {
        observer.observe(self.current);
      }
      return () => {
        observer.disconnect();
      };
    }
    return () => {};
  }, [observed, observationThreshold, self.current, rootNode]);
  return [self, observed, mounted];
};
export default useMountOnObserved;