import {Component, ContextType} from 'react'
import {safeInvoke} from '@befe/brick-utils'
import {ComponentLocale, LocaleTextReplacement} from '../i18n'
import {ThemeConfigWithDefaults} from '../theme'
import {ConfigContext, getDefaultValueUsingContextTheme, getValueFromContextTheme} from './config-context'

export class ConfiguredComponent<
    Props = Record<string, unknown>,
    State = Record<string, unknown>
> extends Component<Props, State> {
    static contextType = ConfigContext
    context!: ContextType<typeof ConfigContext>
    componentLocale?: ComponentLocale

    getLocaleText(key: string, ...args: LocaleTextReplacement[]): string {
        return this.componentLocale && safeInvoke(this.context.getLocaleText, this.componentLocale, key, ...args) || ''
    }

    getThemeValue<TN extends keyof ThemeConfigWithDefaults>(themePropName: TN) {
        return getValueFromContextTheme(this.context, themePropName)
    }

    getDefaultValueUsingTheme<N extends keyof Props, TN extends keyof ThemeConfigWithDefaults>(
        propName: N,
        themePropName: TN
    ) {
        return getDefaultValueUsingContextTheme(this, propName, themePropName)
    }
}
