import { useEffect } from 'react';
import { useRecoilCallback } from 'recoil';
import get from 'lodash/get';
import { pageUpdateTime } from "./index.js";
import useActivateElections from "../../hooks/election/useActivateElections/index.js";
import getElectionInitializer from './getElectionInitializer';
const ElectionHydrator = function ElectionHydrator(props) {
  const {
    flatpackConfig,
    pageBuildTime,
    pageType,
    pagePathPrefix,
    pagesManifest,
    currentPage,
    data,
    electionTimestampFormat
  } = props;

  // Callback to set basic page metadata. This keeps constant page-level
  // metadata consistent and up-to-date as a user navigates through the app
  const callback = useRecoilCallback(({
    set
  }) => () => {
    const init = getElectionInitializer({
      flatpackConfig,
      pageBuildTime,
      pageType,
      pagePathPrefix,
      pagesManifest,
      currentPage,
      electionTimestampFormat,
      set
    });
    init();
  }, [flatpackConfig, pageBuildTime, pageType, pagePathPrefix, pagesManifest, currentPage, electionTimestampFormat]);

  // Callback to reset page udpated time when page ID changes. This atom should
  // be set dynamically by what's rendered on the page, so we only reset it to
  // its default value when the page ID changes, which should signify a user
  // navigating away from the page.
  const pageId = get(currentPage, 'metadata.id', undefined);
  const pageResetCallback = useRecoilCallback(({
    reset
  }) => () => {
    reset(pageUpdateTime(pageId));
  }, [pageId]);
  useActivateElections({
    flatpackConfig,
    dataList: data
  });
  useEffect(() => callback(), [callback]);
  useEffect(() => pageResetCallback, [pageResetCallback]);
  return null;
};
export default ElectionHydrator;