import { useEffect } from 'react';
import { useSetRecoilState } from 'recoil';
import { now, initTime } from "../../../atoms/time/index.js";

/**
 * Hook to initialize periodic updates to the `now` atom. Enables intervals to
 * update as expected. You can configure the interval at which the `now` atom
 * is updated with the `updateInterval` option.
 *
 * Note that this hook should only be called once in your component tree.
 * Multiple calls could cause duplicate updates to the `now` atom.
 *
 * Calling this hook directly is often unnecessary because the `time` atoms can
 * be initialized through the `time` configuration prop passed to the
 * `AtomsRoot` component.
 *
 * @param {Object} opts
 *   Configuration options:
 *   - `updateInterval` is the interval in milliseconds at which the `now` atom
 *     should be updated. If it is less than 0, no updates will happen.
 */
const useInitTime = function useInitTime(opts = {}) {
  const {
    now: nowValue,
    updateInterval = 1000
  } = opts;
  const setNow = useSetRecoilState(now);
  const setInitTime = useSetRecoilState(initTime);
  useEffect(() => {
    setInitTime(new Date());
  }, []);
  useEffect(() => {
    setNow(new Date(nowValue));
  }, [nowValue]);
  useEffect(() => {
    if (updateInterval < 0 || nowValue) return undefined;
    const update = () => setNow(new Date());
    const interval = setInterval(update, updateInterval);
    update();
    return () => clearInterval(interval);
  }, [updateInterval, setNow]);
};
export default useInitTime;