import Taro, { NodesRef, useReady } from '@tarojs/taro';

import { useEffect, useRef, useState } from 'react';

import { CollectEventName } from '@/constants/event';
import { logWithPrefix } from '@/utils/common';
import { collectEvent } from '@/utils/event';

export interface IUseListHeightProps {
  selectors: string[];
  calc: (rects: NodesRef.BoundingClientRectCallbackResult[]) => number;
}

const log = logWithPrefix('useListHeight');

function useListHeight(props: IUseListHeightProps) {
  const [height, setHeight] = useState(Taro.getWindowInfo().screenHeight);
  const isCalculated = useRef(false);

  const calcHeight = () => {
    log('default ListHeight:', height);
    const query = Taro.createSelectorQuery();
    props.selectors.forEach(selector => {
      query.select(selector).boundingClientRect();
    });
    query.exec(function (nodes: NodesRef.BoundingClientRectCallbackResult[]) {
      log('rects:', nodes);
      try {
        const contentHeight = props.calc(nodes);
        log('real ListHeight: ', contentHeight);
        setHeight(contentHeight);
      } catch (e) {
        collectEvent(CollectEventName.DEBUG, {
          action: 'calc_list_height_error',
          selectors: props.selectors,
          nodes: nodes,
        });
      }
    });
  };

  useReady(() => {
    if (isCalculated.current) {
      return;
    }
    isCalculated.current = true;
    calcHeight();
  });

  useEffect(() => {
    if (isCalculated.current) {
      return;
    }
    isCalculated.current = true;
    calcHeight();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  return height;
}

export default useListHeight;
