import { selectorFamily } from 'recoil';
import sortBy from "../../../utils/sorting/sortBy.js";
import delegates from '../atoms/delegates';
import cycleCandidateMetadata from '../atoms/cycleCandidateMetadata';
const sortedDelegateCandidates = selectorFamily({
  key: 'election.selectors.sortedDelegateCandidates',
  get: ({
    party,
    stateFips
  }) => ({
    get
  }) => {
    const partyDelegates = get(delegates(party));
    if (!partyDelegates || !partyDelegates.data) return undefined;
    const unit = stateFips ? partyDelegates.data.states.find(s => s.stateFips === stateFips) : partyDelegates.data;
    if (!unit) return undefined;
    const {
      candidates
    } = unit;
    const candidatesWithMetadata = candidates.map(candidate => {
      const candidateMetadata = get(cycleCandidateMetadata(candidate.id));
      return {
        ...candidate,
        metadata: candidateMetadata?.data
      };
    });
    const sorted = sortBy(candidatesWithMetadata, [{
      comparison: cand => cand.isDropped ? 1 : 0
    }, {
      comparison: 'total',
      direction: 'desc'
    }, {
      comparison: 'metadata.editorialOrder',
      nullFirst: false
    }, {
      comparison: 'metadata.shortName',
      nullFirst: false
    }, {
      comparison: 'id'
    }]);
    return sorted.map(({
      metadata,
      ...restCandidate
    }) => restCandidate);
  }
});
export default sortedDelegateCandidates;