/**
 * WebUtil.java 
 * Copyright © 2015-2015
 * 
 * @author pengdc
 * @create 2015年7月15日
 */
package com.ym.mec.util.web;

import java.util.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ym.mec.util.encode.AES;
import org.apache.commons.lang3.StringUtils;

import static com.ym.mec.util.encode.AES.encrypt;

/**
 * 
 */
public class WebUtil {

	public static String getRandomUUID() {
		UUID uuid = UUID.randomUUID();
		String str = uuid.toString();
		String uuidStr = StringUtils.replace(str, "-", "");
		return uuidStr;
	}

	public static void addCookie(String cookieName, String cookeValue, int age, String domain, String path, HttpServletResponse response) {
		Cookie cookie = new Cookie(cookieName, cookeValue);
		cookie.setMaxAge(age);// 单位：秒
		if (StringUtils.isNotBlank(domain)) {
			cookie.setDomain(domain);
		}
		if (StringUtils.isNotBlank(path)) {
			cookie.setPath(path);
		}
		response.addCookie(cookie);
		// response.addHeader("Set-Cookie", "HttpOnly");// 防止XSS
	}

	public static String getCookie(String key, HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(key)) {
					return cookie.getValue();
				}
			}
		}
		return null;
	}

	public static void removeCookie(String key, String domain, String path, HttpServletResponse response) {
		Cookie cookie = new Cookie(key, null);
		cookie.setMaxAge(0);
		cookie.setPath(path);
		cookie.setDomain(domain);
		response.addCookie(cookie);
	}

	/**
	 * 获取参数
	 * 
	 * @param queryString
	 *            查询字符串
	 * @param encoding
	 *            编码格式
	 * @param name
	 *            参数名称
	 * @return 参数
	 */
	public static Object getParameter(HttpServletRequest request, String name) {
		Map<String, Object> parameterMap = getParameterMap(request);
		return parameterMap.get(name);
	}

	/**
	 * 获取所有参数
	 * 
	 */
	@SuppressWarnings("rawtypes")
	public static Map<String, Object> getParameterMap(HttpServletRequest request) {
		Map<String, Object> parameterMap = new HashMap<String, Object>();
		Object object = null;
		Object[] objs = null;
		Map params = request.getParameterMap();
		Enumeration enu = request.getParameterNames();
		while (enu.hasMoreElements()) {
			String paraName = (String) enu.nextElement();
			object = params.get(paraName);
			if (object != null) {
				if (object.getClass().isArray()) {
					objs = (Object[]) object;
					parameterMap.put(paraName, objs.length == 1 ? objs[0] : objs);
				} else {
					parameterMap.put(paraName, object);
				}
			}
		}
		return parameterMap;
	}

	/**
	 * 获取所有Header参数
	 * 
	 */
	@SuppressWarnings("rawtypes")
	public static Map<String, Object> getHeaderMap(HttpServletRequest request) {
		Map<String, Object> parameterMap = new HashMap<String, Object>();
		Enumeration enu = request.getHeaderNames();
		while (enu.hasMoreElements()) {
			String paraName = (String) enu.nextElement();
			Enumeration headerValues = request.getHeaders(paraName);
			while (headerValues.hasMoreElements()) {
				parameterMap.put(paraName, headerValues.nextElement());
			}
		}
		return parameterMap;
	}

	/**
	 * 获取客户端ip地址
	 * @param request
	 * @return
	 */
	public static String getRemoteIp(HttpServletRequest request) {
		String remoteIp = request.getHeader("x-forwarded-for");
		if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
			remoteIp = request.getHeader("X-Real-IP");
		}
		if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
			remoteIp = request.getHeader("Proxy-Client-IP");
		}
		if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
			remoteIp = request.getHeader("WL-Proxy-Client-IP");
		}
		if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
			remoteIp = request.getHeader("HTTP_CLIENT_IP");
		}
		if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
			remoteIp = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
			remoteIp = request.getRemoteAddr();
		}
		if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
			remoteIp = request.getRemoteHost();
		}
		if (remoteIp != null && remoteIp.indexOf(",") != -1) {
			remoteIp = remoteIp.substring(remoteIp.lastIndexOf(",") + 1, remoteIp.length()).trim();
		}
		return remoteIp;
	}

	/**
	 * 检查访问方式是否为移动端
	 * @param domain cookie所在的域
	 * @param request
	 * @param response
	 */
	public static boolean isFromMobile(String domain, HttpServletRequest request, HttpServletResponse response) {
		boolean isFromMobile = false;
		String cookieKey = "access_resouce__";

		String accessSource = getCookie(cookieKey, request);
		// 检查是否已经记录访问方式（移动端或pc端）
		if (null == accessSource) {
			try {
				// 获取ua，用来判断是否为移动端访问
				String userAgent = request.getHeader("USER-AGENT").toLowerCase();
				if (null == userAgent) {
					userAgent = "";
				}
				isFromMobile = MobileChecker.check(userAgent);

				// 判断是否为移动端访问
				if (isFromMobile) {
					addCookie(cookieKey, "mobile", -1, domain, "/", response);
				} else {
					addCookie(cookieKey, "pc", -1, domain, "/", response);
				}
			} catch (Exception e) {
			}
		} else {
			isFromMobile = "mobile".equals(accessSource);
		}

		return isFromMobile;
	}
}
