package com.winsea.svc.common.international;

import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 国际化配置属性
 *
 * @author SunTianjun
 */
@ConfigurationProperties(prefix = "sys.international")
public class InternationalProperties {

	/**
	 * 是否启用持久化，默认为False
	 */
	private boolean persistenceEnabled = false;

	/**
	 * 是否启用序列化，默认为False
	 */
	private boolean serializationEnabled = false;

	/**
	 * 请求语言参数位置（HEADER/PARAM），默认为HEADER
	 */
	private RequestLangParamPosition paramPosition = RequestLangParamPosition.HEADER;

	/**
	 * 请求语言参数名称，默认为lang
	 */
	private String paramName = "lang";
	
	/**
	 * 默认语言，默认为zh-cn
	 */
	private String defaultLang = "zh-cn";

	public boolean isPersistenceEnabled() {
		return persistenceEnabled;
	}

	public void setPersistenceEnabled(boolean persistenceEnabled) {
		this.persistenceEnabled = persistenceEnabled;
	}

	public boolean isSerializationEnabled() {
		return serializationEnabled;
	}

	public void setSerializationEnabled(boolean serializationEnabled) {
		this.serializationEnabled = serializationEnabled;
	}

	public RequestLangParamPosition getParamPosition() {
		return paramPosition;
	}

	public void setParamPosition(RequestLangParamPosition paramPosition) {
		this.paramPosition = paramPosition;
	}

	public String getParamName() {
		return paramName;
	}

	public void setParamName(String paramName) {
		this.paramName = paramName;
	}

	public String getDefaultLang() {
		return defaultLang;
	}

	public void setDefaultLang(String defaultLang) {
		this.defaultLang = defaultLang;
	}

	/**
	 * 获取请求语言
	 * 
	 * @return 请求语言
	 */
	public String getLang() {
		HttpServletRequest request = null;
		try {
			request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		} catch (Exception ex) {
			// ignore
		}

		if (null == request) {
			return null;
		}

		String lang;
		if (paramPosition == RequestLangParamPosition.HEADER) {
			lang = request.getHeader(paramName);
		} else {
			lang = request.getParameter(paramName);
		}
		return !StringUtils.isBlank(lang) ? lang : defaultLang;
	}

	/**
	 * 请求语言参数位置
	 */
	public enum RequestLangParamPosition {

		HEADER, PARAM
	}
}
