package xyz.wbsite.dbtool.web.frame.utils;

import xyz.wbsite.dbtool.web.frame.auth.LocalData;

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

/**
 * 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 cookies Cookies
     * @return passportID
     */
    public static Cookie newCookie(String key, String value) {
        HttpServletRequest request = LocalData.getRequest();
        Cookie cookie = new Cookie(key, value);
        cookie.setDomain(request.getServerName());
        cookie.setPath(request.getContextPath());
        return cookie;
    }
}
