import { IncomingMessage } from 'http';
import cookie from 'cookie';
import UniversalCookie from 'universal-cookie';

import en from './public/locales/en.json';
import ar from './public/locales/ar.json';
import tr from './public/locales/tr.json';
const langObj: any = { en, ar, tr };

const getLang = (req?: IncomingMessage) => {
    let lang = null;
    if (typeof window !== 'undefined') {
        const cookies = new UniversalCookie();
        lang = cookies.get('i18nextLng');
    } else if (req && req.headers.cookie) {
        const cookies = cookie.parse(req.headers.cookie);
        lang = cookies['i18nextLng'];
    }
    return lang;
};

export const getTranslation = () => {
    const lang = getLang();
    // const lang = "ar";
    const data: any = langObj[lang || 'en'];

    const t = (key: string) => {
        return data[key] ? data[key] : key;
    };

    const initLocale = (themeLocale: string) => {
        const lang = getLang();
        // const lang = "ar";
        i18n.changeLanguage(lang || themeLocale);
    };

    const i18n = {
        language: lang,
        changeLanguage: (lang: string) => {
            const cookies = new UniversalCookie();
            cookies.set('i18nextLng', lang, { path: '/' });
        },
    };

    return { t, i18n, initLocale };
};
