import { useState, useCallback, useLayoutEffect } from "react";

// class DimensionObject {
//     constructor(height, width, top, left, right, bottom, x, y) {
//        // this.height = height;
//         this.width = width;
//         this.top = top;
//         this.left = left;
//         this.right = right;
//         this.bottom = bottom;
//         this.x = x;
//         this.y = y;
//       }
// }


// export type UseDimensionsHook = [
//     (node: HTMLElement) => void,
//     {} | DimensionObject,
//     HTMLElement
// ];


function getDimensionObject(node) {
    const rect = node.getBoundingClientRect();

    
const DimensionsObj = {
    height : rect.height,
    width : rect.width,
    top : "x" in rect ? rect.x : rect.top,
    left: "y" in rect ? rect.y : rect.left,
    x: "x" in rect ? rect.x : rect.left,
    y: "y" in rect ? rect.y : rect.top,
    right: rect.right,
    bottom: rect.bottom
}

    // const obj = new DimensionObject({
    //     width : rect.width,
    //     //height: rect.height,
    //     top: "x" in rect ? rect.x : rect.top,
    //     left: "y" in rect ? rect.y : rect.left,
    //     x: "x" in rect ? rect.x : rect.left,
    //     y: "y" in rect ? rect.y : rect.top,
    //     right: rect.right,
    //     bottom: rect.bottom
    // });

    return DimensionsObj;

}

function useDimensions() {
    const liveMeasure = true;
    const [dimensions, setDimensions] = useState({});
    const [node, setNode] = useState(null);

    const ref = useCallback(node => {
        setNode(node);
    }, []);

    useLayoutEffect(() => {
        if (node) {
            const measure = () =>
                window.requestAnimationFrame(() =>
                    setDimensions(getDimensionObject(node))
                );
            measure();

            if (liveMeasure) {
                window.addEventListener("resize", measure);
                window.addEventListener("scroll", measure);

                return () => {
                    window.removeEventListener("resize", measure);
                    window.removeEventListener("scroll", measure);
                };
            }
        }
    }, [node]);

    return [ref, dimensions, node];

}

export default useDimensions;