package com.huatek.busi.common.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.*;

@Slf4j
public class ResourceHolder {
	
  /**
   * 描述:获取资源文件值
   * 参数：(参数列表).
   * 
   * @param key 国际化key
   * @param language (ZH:中文,EN:英文)
   * @return -
   */
  public static String getText(String key, String language) {
    String value = "";
    String file = "/dev/language/language_zh_CN.properties";
    language = !StrUtil.isBlank(language) ? language.toLowerCase() : "zh";
    if (language.contains("en")) {
      file = "/dev/language/language_en_US.properties";
    } else if (language.equals("zh_TW")) {
      file = "/dev/language/language_zh_TW.properties";
    }
    InputStream stream = null;
    try {
      stream = ResourceHolder.class.getResourceAsStream(file);
      Properties properties = new Properties();
      properties.load(stream);
      value = properties.getProperty(key);
    } catch (IOException exception) {
      log.error("--资源文件取值失败--", exception);
    } finally {
      try {
        if (null != stream) {
          stream.close();
        }
      } catch (IOException ioException) {
        log.error("--流关闭失败--", ioException);
      }
    }
    return value;
  }

  /**
   *
   * @param key 键值
   * @param args 参数数组
   * @param language  语言
   * @return
   */
  public static String getText(String key,Object[] args,String language){
    String text = getText(key,language);
    if(!StrUtil.isEmpty(text) && CollectionUtil.isNotEmpty(Arrays.asList(args))){
      for(int i = 0; i < args.length; i++){
        if(null != args[i]){
          text = text.replace("{"+i+"}",args[i].toString());
        }
      }
    }
    return text;
  }

  /**
   * 描述:获取本地语言
   * 
   * @param language -
   * @return -
   */
  public static Locale getLocale(String language) {
    Locale locale = Locale.CHINESE;
    if (StrUtil.isNotBlank(language)) {
      language = language.toLowerCase();
      if (language.indexOf("en") != -1) {
        locale = Locale.ENGLISH;
      }
      if (language.indexOf("zh_hk") != -1) {
        locale = Locale.TRADITIONAL_CHINESE;
      }
      if (language.indexOf("zh_cn") != -1) {
        locale = Locale.SIMPLIFIED_CHINESE;
      }
    }
    return locale;
  }
}
