package cn.pluss.platform.util;

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

/**
 * TODO
 * cookie 工具类
 * @author crystal
 * @date 2022/6/24 17:29
 */
public class CookieUtils {


    private static final String PREFIX = "SYB-USERID-OPEND-";
    /**
     * 获取value
     * @param request
     * @param key
     * @param isBase64Flag 是否需要转码
     * @return
     */
    public static String getCookieValue(HttpServletRequest request,String key,boolean isBase64Flag){
        String value = null;
        Cookie[] cookies = request.getCookies();
        key = PREFIX + key;
        if (cookies != null && cookies.length > 0) {
            for (Cookie c : cookies) {
                if (key.equals(c.getName())) {
                    value = c.getValue();
                    break;
                }
            }
        }
        if(isBase64Flag && StringUtil.isNotEmpty(value)){
            value = Base64Util.decode(value);
        }
        return value;
    }

    public static void setCookie(HttpServletResponse response,String key, String value,boolean isBase64Flag){
        key = PREFIX + key;
        if(isBase64Flag){
            value = Base64Util.encode(value);
        }
        Cookie cookie = new Cookie(key, value);
        cookie.setMaxAge(-1);
        response.addCookie(cookie);
    }
}
