package com.braintree.configuration.service;

import org.apache.commons.lang.StringUtils;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import static com.braintree.constants.BrainTreeSupportedLocationConstants.CN_COUNTRY;
import static com.braintree.constants.BrainTreeSupportedLocationConstants.DE_COUNTRY;
import static com.braintree.constants.BrainTreeSupportedLocationConstants.DE_LANGUAGE;
import static com.braintree.constants.BrainTreeSupportedLocationConstants.EN_LANGUAGE;
import static com.braintree.constants.BrainTreeSupportedLocationConstants.JA_LANGUAGE;
import static com.braintree.constants.BrainTreeSupportedLocationConstants.JP_COUNTRY;
import static com.braintree.constants.BrainTreeSupportedLocationConstants.US_COUNTRY;
import static com.braintree.constants.BrainTreeSupportedLocationConstants.ZH_LANGUAGE;


public class BrainTreeSupportedLocaleConfig {

    private static final String UNDERSCORE = "_";
    private static final Map<String, Locale> brainTreeSupportedLocaleMap;

    static {
        brainTreeSupportedLocaleMap = new HashMap<>();
        brainTreeSupportedLocaleMap.put(EN_LANGUAGE, new Locale(EN_LANGUAGE, US_COUNTRY));
        brainTreeSupportedLocaleMap.put(JA_LANGUAGE, new Locale(JA_LANGUAGE, JP_COUNTRY));
        brainTreeSupportedLocaleMap.put(DE_LANGUAGE, new Locale(DE_LANGUAGE, DE_COUNTRY));
        brainTreeSupportedLocaleMap.put(ZH_LANGUAGE, new Locale(ZH_LANGUAGE, CN_COUNTRY));
    }

    private BrainTreeSupportedLocaleConfig() {}

    public static String getSupportedLocaleTagByLanguage(final String language) {
        final Locale locale = brainTreeSupportedLocaleMap.get(language);
        return locale.getLanguage() + UNDERSCORE + locale.getCountry();
    }

    public static boolean supportLocale(final String locale) {
        final String languageKey = StringUtils.substringBefore(locale, UNDERSCORE);
        final String countryValue = StringUtils.substringAfter(locale, UNDERSCORE);
        return brainTreeSupportedLocaleMap.get(languageKey).toString().equals(languageKey + UNDERSCORE + countryValue);
    }

    public static String getDefaultLocaleTag(final String currentLocale) {
        final Locale locale = brainTreeSupportedLocaleMap.get(currentLocale);
        return locale.getLanguage() + UNDERSCORE + locale.getCountry();
    }
}
