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

/**
 * 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 source = get(storyCollectionAtom(key));
    if (!source) return undefined;
    const data = {
      ...source.data,
      stories: source.data.stories.filter(story => story.image && story.published)
    };
    return {
      ...source,
      data
    };
  }
});
export default storyCollection;