'use strict';

var _ = require('lodash');
var React = require('react');
var dom = require('../utils/dom.js');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var ___default = /*#__PURE__*/_interopDefault(_);

function getAllSize(classMap) {
  return Object.keys(classMap).reduce((prev, cur) => {
    prev[cur] = dom.getSize(
      document.querySelector(classMap[cur])
    );
    return prev;
  }, {});
}
const elementsSizes = {};
function useElementsSize(classMap, config) {
  const { prevent, key, dependencyList } = config;
  const preSizes = React.useRef();
  const [sizes, setSizes] = React.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 = React.useRef(classMap);
  classMapRef.current = classMap;
  const handleResize = React.useCallback(() => {
    if (prevent)
      return;
    const nextSizes = getAllSize(classMapRef.current);
    if (key) {
      if (!elementsSizes[key] || // FIXME: antd 4.0 table thead will be delay render
      !___default.default.isEqual(
        ___default.default.omit(elementsSizes[key], "thead"),
        ___default.default.omit(nextSizes, "thead")
      )) {
        elementsSizes[key] = nextSizes;
        setSizes(nextSizes);
      }
    } else if (!___default.default.isEqual(preSizes.current, nextSizes)) {
      preSizes.current = nextSizes;
      setSizes(nextSizes);
    }
  }, [prevent, key, ...dependencyList || []]);
  React.useLayoutEffect(() => {
    handleResize();
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, [handleResize]);
  return sizes;
}

module.exports = useElementsSize;
