import { computed, inject } from '@angular/core';
import type {
DictionaryKeys,
DictionaryRegistryContent,
LocalesValues,
} from '@intlayer/types';
import { getIntlayer } from '../getIntlayer';
import type { DeepTransformContent } from '../plugins';
import { INTLAYER_TOKEN, type IntlayerProvider } from './installIntlayer';
/** guard utility - true only for objects generated by `renderIntlayerNode()` */
export const isUpdatableNode = (
val: unknown
): val is { __update: (n: unknown) => void } =>
!!val &&
typeof val === 'object' &&
typeof (val as any).__update === 'function';
export const useIntlayer = <T extends DictionaryKeys, L extends LocalesValues>(
key: T,
locale?: LocalesValues
): DeepTransformContent<DictionaryRegistryContent<T>> => {
const intlayer = inject<IntlayerProvider>(INTLAYER_TOKEN)!;
/** which locale should we use right now? */
const localeTarget = computed(() => locale ?? intlayer.locale());
/** a *stable* reactive dictionary object */
// @ts-ignore Type instantiation is excessively deep and possibly infinite
const content = computed(() => getIntlayer<T, L>(key, localeTarget() as L));
return content() as DeepTransformContent<DictionaryRegistryContent<T>>; // all consumers keep full reactivity
};