import { useEffect, useState } from 'react';

export function useScript(src: string) {
	const [loading, setLoading] = useState(true);
	const [error, setError] = useState(null);

	useEffect(() => {
		let script = document.querySelector(`script[src="${src}"]`);
		
		const handleLoad = () => setLoading(false);
		const handleError = (err: any) => {
			setError(err);
			setLoading(false);
		};
		if(!script){
			script = document.createElement('script');
			(script as any).src = src;
			(script as any).type = 'text/javascript';
			(script as any).charset = 'utf-8';

			script.addEventListener('load', handleLoad);
			script.addEventListener('error', handleError);
			console.log(script);
			// document.getElementsByTagName('head')[0].appendChild(script);
		}
		else{
			setLoading(false);
		}

		return () => {
			script.removeEventListener('load', handleLoad);
			script.removeEventListener('error', handleError);
		}
	}, [src]);

	return [loading, error];
}