package com.ffii.core.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.i18n.LocaleContextHolder;

import java.util.Locale;

/** this utils follow "-" standard ("zh-TW", no "zh_TW") */
public abstract class LocaleUtils {

  public static Locale getLocale() {
    return LocaleContextHolder.getLocale();
  }

  public static String getLocaleStr() {
    return toLocaleStr(LocaleContextHolder.getLocale());
  }

  public static String toLocaleStr(Locale locale) {
    String language = locale.getLanguage();
    String country = locale.getCountry();

    if (StringUtils.isNotBlank(country)) {
      return language + "-" + country;
    } else {
      return language;
    }
  }

  /**
   * @param localeStr
   *          e.g. zh-TW
   */
  public static Locale from(String localeStr) {
    String[] localeArr = localeStr.split("-");
    if (localeArr.length == 1) {
      return new Locale(localeArr[0]);
    } else {
      return new Locale(localeArr[0], localeArr[1]);
    }
  }
}
