import { selectorFamily } from 'recoil';
import lodashGet from 'lodash/get';
import storyCollectionAtom from '../atoms/storyCollection';
const filterStories = data => {
  const type = lodashGet(data, 'feed.type');
  if (type === 'liveblog') return data.stories;
  return data.stories.filter(story => story.image && story.published);
};

/**
 * 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: filterStories(source.data)
    };
    return {
      ...source,
      data
    };
  }
});
export default storyCollection;