import { length, equals, prop, values } from "ramda";

import { useCallback, useEffect, useState } from "react";
import { useScreenTrackedViewPositionsContext } from "@applicaster/zapp-react-native-ui-components/Contexts/ScreenTrackedViewPositionsContext";
import { findTrackedView } from "./utils/findTrackedView";

const CHECK_INTERVAL = 500;

const componentIdOf = prop("componentId");

export const useTrackCurrentAutoScrollingElement = (componentId) => {
  const { value: componentsPositions } = useScreenTrackedViewPositionsContext();

  const [isCurrentlyAutoScrolling, setIsCurrentlyAutoScrolling] =
    useState(false);

  const checkActive = useCallback(() => {
    const array = values(componentsPositions);

    if (length(array ?? [])) {
      const isActive = equals(
        componentIdOf(findTrackedView(array)),
        componentId
      );

      setIsCurrentlyAutoScrolling(isActive);
    }
  }, [componentId]);

  useEffect(() => {
    const timer = setInterval(checkActive, CHECK_INTERVAL);

    return () => {
      clearInterval(timer);
    };
  }, [checkActive]);

  return isCurrentlyAutoScrolling;
};
