// Libs
// -----------------------------------------------------------------------------
import { useCallback } from 'react';

// App
// -----------------------------------------------------------------------------
import { GenericDataStore } from 'stores/GenericDataStore';
import { InterfaceWithIdAndName } from 'types/default';
import {
  openNotificationError,
  openNotificationSuccess,
  useProgressNotification,
} from 'components/Messages';
import { Notification } from 'components/types';
import { useCommonMessages } from 'components/i18n';

// Интерфейс расширенного GenericDataStore с поддержкой экспорта
interface InterfaceDataStoreWithExport<
  T extends InterfaceWithIdAndName,
  TB extends InterfaceWithIdAndName = T,
> extends GenericDataStore<T, TB> {
  exportData: () => Promise<void>;
}

// Интерфейс локали с полями уведомлений экспорта
interface InterfaceLocaleWithExportMessages {
  exportSuccessTitle: string;
  exportSuccessSubtitle?: string;
  exportFailureTitle: string;
  exportFailureSubtitle?: string;
}

export const useExportData = <
  T extends InterfaceWithIdAndName,
  TB extends InterfaceWithIdAndName = T,
>(
  dataStore: InterfaceDataStoreWithExport<T, TB>,
  dashboardLocale: InterfaceLocaleWithExportMessages,
): (() => Promise<void>) => {
  const commonLocale = useCommonMessages();

  // Показать/скрыть уведомление с прогрессом операции
  const { activateProgressMessage, stopProgressMessage } =
    useProgressNotification({
      key: 'progress',
      title: commonLocale.notification[Notification.ProgressTitle],
      makeDescription: (seconds) =>
        seconds
          ? commonLocale.notification[Notification.ProgressSubTitle](seconds)
          : '',
    });

  return useCallback(async (): Promise<void> => {
    activateProgressMessage();
    try {
      await dataStore.exportData();

      stopProgressMessage();

      openNotificationSuccess({
        messageTitle: dashboardLocale.exportSuccessTitle,
        messageDescription: dashboardLocale.exportSuccessSubtitle,
      });
    } catch {
      stopProgressMessage();
      openNotificationError({
        messageTitle: dashboardLocale.exportFailureTitle,
      });
    }
  }, [
    dataStore,
    dashboardLocale,
    activateProgressMessage,
    stopProgressMessage,
  ]);
};
