import { ScopeNotGrantedError } from './errors.mjs';
import { useApi } from './api.mjs';
import { useSubscription } from './subscription.mjs';

/**
 * Returns the current localized fields and
 * re-renders your component if the values change.
 */
function useLocalizedFields(keys) {
  const {
    localizedFields
  } = useApi();
  if (!localizedFields) {
    throw new ScopeNotGrantedError('Using localized fields requires having personal customer data permissions granted to your app.');
  }
  const localizedFieldsData = useSubscription(localizedFields);
  if (!keys) {
    return localizedFieldsData;
  }
  if (!keys.length) {
    return [];
  }
  return localizedFieldsData.filter(({
    key
  }) => keys.includes(key));
}

/**
 * Returns the current localized field or undefined for the specified
 * localized field key and re-renders your component if the value changes.
 */
function useLocalizedField(key) {
  const fields = useLocalizedFields([key]);
  return fields[0];
}

export { useLocalizedField, useLocalizedFields };
