import _ from 'lodash';
import { useRef, useState, useCallback, useLayoutEffect } from 'react';
import { getSize } from '../utils/dom.js';

function getAllSize(classMap) {
  return Object.keys(classMap).reduce((prev, cur) => {
    prev[cur] = getSize(
      document.querySelector(classMap[cur])
    );
    return prev;
  }, {});
}
const elementsSizes = {};
function useElementsSize(classMap, config) {
  const { prevent, key, dependencyList } = config;
  const preSizes = useRef();
  const [sizes, setSizes] = useState(() => {
    if (key && elementsSizes[key]) {
      return elementsSizes[key];
    }
    const initSizes = Object.keys(classMap).reduce((prev, cur) => {
      prev[cur] = { width: 0, height: 0 };
      return prev;
    }, {});
    preSizes.current = initSizes;
    return initSizes;
  });
  const classMapRef = useRef(classMap);
  classMapRef.current = classMap;
  const handleResize = useCallback(() => {
    if (prevent)
      return;
    const nextSizes = getAllSize(classMapRef.current);
    if (key) {
      if (!elementsSizes[key] || // FIXME: antd 4.0 table thead will be delay render
      !_.isEqual(
        _.omit(elementsSizes[key], "thead"),
        _.omit(nextSizes, "thead")
      )) {
        elementsSizes[key] = nextSizes;
        setSizes(nextSizes);
      }
    } else if (!_.isEqual(preSizes.current, nextSizes)) {
      preSizes.current = nextSizes;
      setSizes(nextSizes);
    }
  }, [prevent, key, ...dependencyList || []]);
  useLayoutEffect(() => {
    handleResize();
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, [handleResize]);
  return sizes;
}

export { useElementsSize as default };
