import { useState, useCallback } from 'react';
const useCallAd = function useCallAd({
  id,
  type,
  retryLimit = 10
}) {
  const [mounted, setMounted] = useState(false);
  const callAd = useCallback(() => {
    const tryToMount = retries => new Promise(resolve => {
      if (!mounted) {
        if (id && window.generateCustomAds) {
          try {
            window.generateCustomAds(`#${id}`, type);
            setMounted(true);
            resolve();
          } catch (error) {
            /* eslint-disable-next-line no-console */
            console.error('Ad: Error Generating Ad: ', error);
          }
        } else if (retries < retryLimit) {
          setTimeout(() => {
            tryToMount(retries + 1);
          }, 1000);
        } else {
          /* eslint-disable-next-line no-console */
          console.error('Ad: Advertising network not loaded.');
        }
      }
    });
    tryToMount(0);
  }, [id, type, mounted]);
  return [callAd, mounted];
};
export default useCallAd;