import { selectorFamily } from 'recoil';
import storyCollectionAtom from '../atoms/storyCollection';
import multiSourceData from './multiSourceData';

/**
 * The `storyCollection` selector provides a read-write interface for story
 * collections. It passes writes directly through to the underlying
 * `storyCollection` atom family, but on reads it provides the default value of
 * an empty collection.
 */
const storyCollection = selectorFamily({
  key: 'election.selectors.storyCollection',
  get: key => ({
    get
  }) => {
    const collection = storyCollectionAtom(key);
    const source = get(multiSourceData(collection.key));
    if (!source) return undefined;
    const data = {
      ...source.data,
      stories: source.data.stories.filter(story => story.image && story.published)
    };
    return {
      data,
      source
    };
  }
});
export default storyCollection;