import { useState, useLayoutEffect } from 'react';

/**
    Used for a component to report its dimensions on each render and when its content images are loaded
*/
export const ReportRect = (contentRef, onRecomputed) => {
    const [imagesLoaded, setImagesLoaded] = useState(false);

    const recompute = () => {
        if (contentRef.current) {
            onRecomputed(contentRef.current.getBoundingClientRect());
        }
    };

    useLayoutEffect(
        // eslint-disable-next-line consistent-return
        () => {
            recompute();

            // adds listeners to relayout when all images will be loaded
            if (!imagesLoaded && contentRef.current) {
                const images = Array.from(contentRef.current.querySelectorAll('img'));
                if (!images.length) {
                    setImagesLoaded(true);
                }
                // is there an unloaded image amongst the images?
                const hasNotLoaded = images.find(img => !img.complete || !img.naturalWidth);
                if (hasNotLoaded) {
                    images.forEach(img => (
                        img.addEventListener('load', recompute)
                    ));
                    // cleanup on unmount
                    return () => {
                        images.forEach(img => (
                            img.removeEventListener('load', recompute)
                        ));
                    };
                }
                setImagesLoaded(true);
            }
        }
    );
};
