import { IGetLocalizedValueOptions, ILocalizedValue, getLocalizedValue } from '@/utils';
import { useLocaleState } from 'ra-core';
import { useCallback } from 'react';

function useLocale(locale?: string): string {
  const [defaultLocale] = useLocaleState();

  return locale !== undefined ? String(locale) : defaultLocale;
}

type IUseLocalizeValueOptions = IGetLocalizedValueOptions & {
  locale?: string;
};
function useLocalizedValue<T>(value: ILocalizedValue<T>, options?: IUseLocalizeValueOptions): T | undefined {
  const language = useLocale(options?.locale);
  const localizedValue = getLocalizedValue<T>(value, language, options);

  return localizedValue;
}

type IUseGetLocalizeValueOptions = IUseLocalizeValueOptions;
function useGetLocalizedValue<T>(options?: IUseGetLocalizeValueOptions): (v: ILocalizedValue<T>) => T | undefined {
  const language = useLocale(options?.locale);
  const callback = useCallback(
    (value: ILocalizedValue<T>) => {
      return getLocalizedValue<T>(value, language, options);
    },
    [language, options]
  );

  return callback;
}

export { useGetLocalizedValue, useLocalizedValue };
