import { useEffect, useState, useRef, useMemo } from 'react';
import differenceBy from 'lodash/differenceBy';
import { useCallFeed } from "../../../hooks/election/index.js";
const CALL_DURATION = 30000;
export default function useTrackCalls(collectionId, importantOnly) {
  const feed = useCallFeed(collectionId);
  const filteredCalls = useMemo(() => {
    if (!feed) {
      return undefined;
    }
    return feed.calls.filter(c => {
      const isImportant = c?.custom?.important;
      return importantOnly ? isImportant : !isImportant;
    });
  }, [importantOnly, feed]);
  const previousFeed = useRef();
  const [newCalls, setNewCalls] = useState([]);
  const [displayIdx, setDisplayIdx] = useState();
  const activeInterval = useRef();

  // Add new calls into the queue
  useEffect(() => {
    if (!filteredCalls) {
      return;
    }
    if (!previousFeed.current) {
      previousFeed.current = JSON.parse(JSON.stringify(filteredCalls));
      return;
    }
    const getId = c => c.call?.contestId ?? c.custom?.id;
    const newCallsInFeed = differenceBy(filteredCalls, previousFeed.current, getId).map(getId);
    setNewCalls(s => [...s, ...newCallsInFeed]);
    setDisplayIdx(i => {
      if (newCallsInFeed.length > 0 && typeof i === 'undefined') {
        return 0;
      }
      return i;
    });
    previousFeed.current = JSON.parse(JSON.stringify(filteredCalls));
  }, [filteredCalls]);
  useEffect(() => {
    if (typeof displayIdx === 'undefined' || displayIdx >= newCalls.length || activeInterval.current || newCalls.length === 0) {
      return;
    }
    activeInterval.current = setTimeout(() => {
      setDisplayIdx(i => i + 1);
      activeInterval.current = undefined;
    }, CALL_DURATION);
  }, [newCalls, displayIdx]);
  return [newCalls, displayIdx];
}