import { selector } from 'recoil';
import sortBy from "../../../utils/sorting/sortBy.js";
import { getStateName } from "../../../utils/election/index.js";
import pagesManifestAtom from '../atoms/pagesManifest';
import currentPageAtom from '../atoms/currentPage';

/**
 * Collect the current set of pages to display in various navigational
 * interfaces.
 */
const navigationPages = selector({
  key: 'election.selectors.navigationPages',
  get: ({
    get
  }) => {
    const manifest = get(pagesManifestAtom);
    const currentPage = get(currentPageAtom);
    const initial = {
      globalPages: [],
      drawerPages: [],
      statePages: [],
      states: []
    };
    if (!manifest) return initial;
    const config = manifest.pages.reduce((cfg, page) => {
      const {
        nav,
        stateFips
      } = page;
      if (!nav) return cfg;
      if (nav.level === 'global') {
        cfg.globalPages.push(page);
      }
      if (['global', 'drawer'].includes(nav.level)) {
        cfg.drawerPages.push(page);
      }
      if (nav.level.startsWith('state')) {
        cfg.states.add(stateFips);
      }
      if (!currentPage) return cfg;
      if (currentPage.metadata.stateFips && currentPage.metadata.nav.level === nav.level) {
        cfg.statePages.push(page);
      }
      return cfg;
    }, {
      globalPages: [],
      drawerPages: [],
      statePages: [],
      states: new Set()
    });
    const roleValues = {
      index: 1,
      president: 2,
      senate: 3,
      house: 4,
      governor: 5,
      lieutenantGovernor: 6,
      other: 7
    };
    const getPageRoleValue = page => {
      const values = page.roles.map(role => {
        const [roleLevel, indexRoleName, stateRoleName] = role.split(':');
        if (roleLevel === 'index') return roleValues[indexRoleName];
        if (roleLevel === 'state') return roleValues[stateRoleName];
        return undefined;
      });
      return Math.min(...values);
    };
    const pageComparisons = [{
      comparison: page => getPageRoleValue(page)
    }, {
      comparison: page => page.nav.name
    }];
    const sortedGlobalPages = sortBy(config.globalPages, pageComparisons);
    const sortedStatePages = sortBy(config.statePages, pageComparisons);
    const sortedDrawerPages = sortBy(config.drawerPages, pageComparisons);
    const states = [...config.states].filter(fips => getStateName(fips));
    return {
      ...config,
      globalPages: sortedGlobalPages,
      drawerPages: sortedDrawerPages,
      statePages: sortedStatePages,
      states: sortBy(states, [{
        comparison: fips => getStateName(fips)
      }]),
      currentPage
    };
  }
});
export default navigationPages;