import { selector } from 'recoil';
import us from 'us';
import lodashGet from 'lodash/get';
import sortBy from "../../../utils/sorting/sortBy.js";
import calendarAtom from '../atoms/calendar';
const customCalendarNames = {
  'Washington, D.C.': 'District of Columbia',
  'U.S. Virgin Islands': 'Virgin Islands'
};

/**
 * Election calendar data.
 */
const calendar = selector({
  key: 'election.selectors.calendar',
  get: ({
    get
  }) => {
    const source = get(calendarAtom);
    if (!source || !source.data) return undefined;
    const getFips = name => {
      const stateName = customCalendarNames[name] || name;
      return lodashGet(us.lookup(stateName), 'fips');
    };
    const namedElectionsSortedByDate = sortBy(source.data.content.namedElections, [{
      comparison: 'date',
      direction: 'asc',
      type: 'date'
    }, 'label']);
    const electionEventsSortedByDate = sortBy(source.data.content.electionEvents, [{
      comparison: 'date',
      direction: 'asc',
      type: 'date'
    }, 'state']);
    const data = {
      ...source.data.content,
      namedElections: namedElectionsSortedByDate.map(election => ({
        ...election,
        date: election.date.slice(0, 'YYYY-MM-DD'.length)
      })),
      electionEvents: electionEventsSortedByDate.map(election => ({
        ...election,
        date: election.date.slice(0, 'YYYY-MM-DD'.length),
        stateFips: getFips(election.state)
      }))
    };
    return {
      data,
      source
    };
  }
});
export default calendar;