import "core-js/modules/es.array.iterator.js";
import "core-js/modules/web.dom-collections.iterator.js";
import { useState, useCallback, useEffect } from 'react';
import { appendScript } from './utils';
export const useMapLoad = (key, onLoaded) => {
  const [error, setError] = useState();
  const [loading, setLoading] = useState(true);
  const loadScript = useCallback(() => {
    setError(undefined);
    const cb = `mapLoadCb${Math.ceil(Math.random() * Math.pow(10, 16)).toString(16)}`;
    window[cb] = (...args) => {
      onLoaded(...args);
    };
    const script = appendScript(key, cb);
    script.addEventListener('error', err => {
      setError(err);
      setLoading(false);
    });
    script.addEventListener('load', () => {
      setLoading(false);
    });
    script.addEventListener('loadstart', () => {
      setLoading(true);
    });
    return () => {
      delete window[cb];
    };
  }, [key, onLoaded]);
  useEffect(() => {
    loadScript();
  }, [loadScript]);
  return {
    loading,
    error,
    loadScript
  };
};