import i18n from 'i18next';
import React from 'react';
import { I18nextProvider, initReactI18next } from 'react-i18next';
import { AttachmentContextProvider } from '../components/shared/fileUpload/AttachmentReducerContext';
import { initializeTranslations } from '../i18n/utils/translation-helper';
import { AppMetadataContextProvider } from './AppMetadataContext';
import { CreateCaseContextProvider } from './CreateCaseContext';
import { RecommendationContextProvider } from './RecommendationContext';
import { RouteContextProvider } from './RouteContext';
import { RulesContextProvider } from './RulesContext';

interface IProps {
    children: JSX.Element | JSX.Element[];
}

initializeTranslations().then((resources) => {
    i18n.use(initReactI18next).init({
        lng: resources && resources.lang || 'en',
        interpolation: {
            escapeValue: false
        },
        resources: resources && resources.translation,
        react: {
            wait: true
        },
        nsSeparator: ':::',
        keySeparator: '::',
        debug: false
    });

    /*
    * Using translation has never been this fun
    * To use translation there are 2 way
    * 1. Using <Trans /> component
    * Let's try to translate "+3 more points"
    * import { Trans } from 'react-i18next';
    * <Trans>+{{more: props.more}} more points</Trans>
    * Trans component allow you to use it with links and different tags inside it
    * 2. You can also use getText()
    * getText('+{{more}} more points', {{more: props.more}})
    */
})
    .catch((error) => {
        // tslint:disable-next-line:no-console
        console.error(error);
    });

export function getText(key: string, args?: object): string {
    return i18n.t(key, args);
}

export default function RootProvider(props: IProps) {
    return (
        <I18nextProvider i18n={i18n}>
            <RouteContextProvider>
                <AppMetadataContextProvider>
                    <CreateCaseContextProvider>
                        <RecommendationContextProvider>
                            <AttachmentContextProvider>
                                <RulesContextProvider>
                                    {props.children}
                                </RulesContextProvider>
                            </AttachmentContextProvider>
                        </RecommendationContextProvider>
                    </CreateCaseContextProvider>
                </AppMetadataContextProvider>
            </RouteContextProvider>
        </I18nextProvider>
    );
}
