import groupBy from 'lodash/groupBy';
import { useMemo } from 'react';
import { easeInOutCubic } from "../../../../utils/ease/index.js";
import sortBy from "../../../../utils/sorting/sortBy.js";
export default function useLines(data, scales, range) {
  const processedData = useMemo(() => {
    const groupedData = groupBy(data, 'fips');
    return Object.values(groupedData).map(stateGroup => {
      const years = sortBy(stateGroup, [{
        comparison: 'year'
      }]);
      return years.reduce((acc, start, idx) => {
        const end = years[idx + 1];
        if (!end) {
          acc.push(start);
          return acc;
        }
        acc.push(start);
        const steps = 10;
        const stepSize = (end.year - start.year) / (steps + 1);
        for (let i = 1; i <= steps; i += 1) {
          const t = i / (steps + 1);
          const easedT = easeInOutCubic(t);
          const intermediateYear = start.year + stepSize * i;
          const intermediateValue = start.value + easedT * (end.value - start.value);
          acc.push({
            year: intermediateYear,
            fips: start.fips,
            value: intermediateValue
          });
        }
        return acc;
      }, []);
    });
  }, [data]);
  return useMemo(() => {
    const lines = processedData.map(state => ({
      fips: state[0].fips,
      end: state[state.length - 1],
      continue: !state.find(s => s.year === range.y.max),
      d: scales.line(state)
    }));
    return sortBy(lines, ['end.value', 'fips']);
  }, [processedData, scales]);
}