package org.fouram.core.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

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

/**
 * 处理cookie公用类
 * 
 * @author liupeng
 * 
 */
public class CookieUtil {

	private HttpServletRequest request;
	private HttpServletResponse response;
	private int age;// 设置cookie经过多长秒后被删除

	public CookieUtil(HttpServletRequest request, HttpServletResponse response, int age) {
		this.request = request;
		this.response = response;
		this.age = age;
	}

	public CookieUtil(HttpServletRequest request, HttpServletResponse response) {
		this.request = request;
		this.response = response;
	}

	/**
	 * 添加cookie
	 * 
	 * @param name
	 * @param value
	 * @throws UnsupportedEncodingException 
	 */
	public void addCookie(String name, String value) throws UnsupportedEncodingException {
		Cookie cookies = new Cookie(name, URLEncoder.encode(value, "UTF-8"));
		cookies.setPath("/");
		cookies.setMaxAge(age);
		response.addCookie(cookies);
	}
	
	/**
	 * 根据cookieName获取cookie值
	 * 
	 * @param cookieName
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	public String getCookieValue(String cookieName) {
		if (cookieName != null) {
			Cookie cookie = getCookie(cookieName);
			String cookieValue = "";
			if (cookie != null) {
				try {
					cookieValue = URLDecoder.decode(cookie.getValue(), "UTF-8");
				} catch (UnsupportedEncodingException e) {
					LoggerUtil.error(e);
				}
				return cookieValue;
			}
		}
		return "";
	}

	/**
	 * 根据cokkieName获取cookie
	 * 
	 * @param cookieName
	 * @return
	 */
	public Cookie getCookie(String cookieName) {
		Cookie[] cookies = request.getCookies();
		Cookie cookie = null;
		try {
			if (cookies != null && cookies.length > 0) {
				for (int i = 0; i < cookies.length; i++) {
					cookie = cookies[i];
					if (cookie.getName().equals(cookieName)) {
						return cookie;
					}
				}
			}
		} catch (Exception e) {
			LoggerUtil.error(e);
		}
		return null;
	}

	/**
	 * 删除cookieName对应cookie
	 * 
	 * @param cookieName
	 * @return
	 */
	public boolean deleteCookie(String cookieName) {
		if (cookieName != null) {
			Cookie cookie = getCookie(cookieName);
			if (cookie != null) {
				cookie.setMaxAge(0);// 如果0，就说明立即删除
				cookie.setPath("/");// 不要漏掉
				response.addCookie(cookie);
				return true;
			}
		}
		return false;
	}
}