import { selectorFamily } from 'recoil';
import multiSourceMetadata from '../atoms/multiSourceMetadata';
import dataSource from './dataSource';

/**
 * The `multiSourceData` family provides a way to select the most recently
 * updated data from multiple sources that can provide it.
 */
const multiSourceData = selectorFamily({
  key: 'election.selectors.multiSourceData',
  get: key => ({
    get
  }) => {
    const meta = get(multiSourceMetadata(key));
    const newestSource = meta.reduce((newest, source) => {
      if (!newest) return source;
      if (source.lastUpdated > newest.lastUpdated) return source;
      return newest;
    }, null);
    if (!newestSource) return undefined;
    return get(dataSource(newestSource.key));
  }
});
export default multiSourceData;