package com.keao.edu.common.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.keao.edu.common.config.ParameterCheckServletRequestWrapper;
import com.vdurmont.emoji.EmojiParser;

public class EmojiEncodingFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		Filter.super.init(filterConfig);
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		request = new ParameterCheckServletRequestWrapper((HttpServletRequest) request) {

			@Override
			public String getParameter(String name) {
				// 参数名
				String value = super.getParameter(name);
				if (StringUtils.isNotBlank(value)) {
					// 返回值之前 先进行 Emoji 转化
					return EmojiParser.removeAllEmojis(value);
				}
				return value;
			}

			@Override
			public String[] getParameterValues(String name) {
				// 参数值
				// 返回值之前 先进行 Emoji 转化
				String[] values = super.getParameterValues(name);
				if (values != null) {
					for (int i = 0; i < values.length; i++) {
						values[i] = EmojiParser.removeAllEmojis(values[i]);
					}
				}
				return values;
			}

		};
		
		chain.doFilter(request, response);
	}

}
