import { useMemo } from 'react';
import groupBy from 'lodash/groupBy';
import sortBy from "../../../utils/sorting/sortBy.js";
import { FIRST_AD_GROUP_SIZE, MIN_AD_GROUP_SIZE, SECOND_AD_GROUP_SIZE } from './constants';
const useAdSections = (collectionMetadata, notes) => useMemo(() => {
  if (!collectionMetadata) {
    return [];
  }
  const notesAndContests = {
    ...collectionMetadata,
    ...notes
  };
  const contestsByDistrict = groupBy(Object.values(notesAndContests), d => d.districtNumber);
  const districtNumbers = Object.keys(contestsByDistrict);
  const districts = districtNumbers.map(d => {
    const contests = sortBy(contestsByDistrict[d], ['party', 'isSpecial'], 'asc', 'string');

    // TO DO: handle if there's a note given for a contest that already exists?
    // but would we do that?
    return {
      districtNumber: d,
      contests
    };
  });
  const sortedDistricts = sortBy(districts, ['districtNumber'], 'asc', 'number');
  const totalDistricts = sortedDistricts.length;

  // We do not want to split the districts unless we'd have a least the minimum
  // required districts between the ad and the bottom of the page.

  if (totalDistricts < FIRST_AD_GROUP_SIZE + MIN_AD_GROUP_SIZE) {
    return [{
      id: 'ad-group-start-full',
      group: sortedDistricts
    }];
  }

  // Otherwise, split the districts
  // First ad comes after the $FIRST_AD_GROUP_SIZE number of districts
  const firstGroup = sortedDistricts.slice(0, FIRST_AD_GROUP_SIZE);
  const adGroups = [{
    id: 'first',
    group: firstGroup
  }];

  // Then after every eight
  for (let i = FIRST_AD_GROUP_SIZE; i < totalDistricts; i += SECOND_AD_GROUP_SIZE) {
    const nextEndIdx = i + SECOND_AD_GROUP_SIZE;
    let group = sortedDistricts.slice(i, nextEndIdx);
    if (nextEndIdx > totalDistricts - MIN_AD_GROUP_SIZE) {
      // If we'd have less than two districts in the last group,
      // just add them to the one we have right now
      group = sortedDistricts.slice(i, totalDistricts);
      i = totalDistricts;
    }
    adGroups.push({
      id: `ad-group-start-${i}`,
      group
    });
  }
  return adGroups;
}, [collectionMetadata]);
export default useAdSections;