import { useQuery } from 'react-query';

import { getCalendarEvent } from 'src/services/events';
import { downloadFile, getIcsFileName } from 'src/utils/files';

import { eventsKeys } from '../queries';

export const useDownloadCalendar = (id: number) => {
  const { isLoading: isLoadingCalendar, refetch } = useQuery(
    eventsKeys.eventCalendar(id),
    () => getCalendarEvent(id),
    {
      enabled: false,
      select: r => r.data,
      onSuccess(data) {
        const fileName = getIcsFileName(data);
        downloadFile(data, fileName);
      },
    },
  );

  return { isLoadingCalendar, downloadCalendarEvent: refetch };
};

export default useDownloadCalendar;
