package ${basePackage}.frame.utils;

import ${basePackage}.frame.auth.LocalData;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * CookieUtil
 *
 * @author wangbing
 * @version 0.0.1
 * @since 2017-01-01
 */
public class CookieUtil {

    /**
     * 通过Cookies获取内容
     *
     * @param cookies Cookies
     * @return passportID
     */
    public static String getCookieValue(Cookie[] cookies, String key) {
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                // Cookie中存放的为passport的id ，Cookie名称通过ConfigToolObject获取
                if (cookie != null && cookie.getName().equals(key)) {
                    try {
                        return cookie.getValue();
                    } catch (Exception ignored) {
                    }
                }
            }
        }
        return null;
    }

    /**
     * 生成一个默认的Cookie
     *
     * @param name  键
     * @param value 值
     */
    public static Cookie newCookie(String name, String value) {
        HttpServletRequest request = LocalData.getRequest();
        Cookie cookie = new Cookie(name, value);
        cookie.setDomain(request.getServerName());
        cookie.setMaxAge(-1);
        cookie.setPath("/");
        return cookie;
    }

    /**
     * 删除一个Cookie
     *
     * @param name 键
     */
    public static void clearCookie(String name) {
        HttpServletRequest request = LocalData.getRequest();
        HttpServletResponse response = LocalData.getResponse();
        Cookie cookie = new Cookie(name, null);
        cookie.setDomain(request.getServerName());
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}