import { selectorFamily } from 'recoil';
import dataSourceAtom from '../atoms/dataSource';
import reformat from '../utils/reformat';
import updateAtomSources from '../utils/updateAtomSources';
import updateCrossTables from '../utils/updateCrossTables';

/**
 * The `dataSource` family provides a way to select the most recently updated
 * data from multiple sources that can provide it.
 */
const dataSource = selectorFamily({
  key: 'election.selectors.dataSource',
  get: key => ({
    get
  }) => get(dataSourceAtom(key)),
  set: key => ({
    set
  }, data) => {
    const {
      status = 'raw',
      value
    } = data;
    const reformattedData = status === 'raw' ? reformat(value) : value;
    set(dataSourceAtom(key), reformattedData);
    updateAtomSources({
      set,
      key,
      source: reformattedData
    });
    updateCrossTables({
      set,
      source: reformattedData
    });
  }
});
export default dataSource;