import { DateTime } from "luxon";

import { DashboardFilter } from "../../../contexts/DashboardFilterContext";
import { Granularity } from "../../../types/dashboard";

export const diffDatesByGranularity = (
  startDate: DateTime,
  endDate: DateTime,
  granularity: Granularity,
): number => {
  switch (granularity) {
    case "week":
      return Math.ceil(endDate.diff(startDate, "weeks").weeks);
    case "month":
      return Math.ceil(endDate.diff(startDate, "months").months);
    case "quarter":
      return Math.ceil(endDate.diff(startDate, "quarters").quarters);
    case "year":
      return Math.ceil(endDate.diff(startDate, "years").years);
    default:
      return Math.ceil(endDate.diff(startDate, "days").days);
  }
};

/**
 * Calculate the difference between two dates based on `DashboardFilter.granularity`.
 * Defaults to the _inclusive_ end date.
 */
export const diffDatesByGranularityWithFilter = ({
  startDate,
  endDate,
  granularity,
}: DashboardFilter): ReturnType<typeof diffDatesByGranularity> =>
  diffDatesByGranularity(startDate, endDate, granularity);
