package me.qwq.doghouse.util;

import jakarta.servlet.http.Cookie;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import me.qwq.doghouse.annotation.StaticAttribute;
import me.qwq.doghouse.entity.User;

@StaticAttribute
public class CookieUtils {
    
    public static final String PASSWORD_COOKIE = "postPassword";
    public static final String COMMENT_AUTHOR = "comment_author";
    public static final String COMMENT_URL = "comment_url";
    public static final String COMMENT_EMAIL = "comment_email";
    
    public static void setUserToCookie(HttpServletResponse response, User user) {

        Cookie commentAuthor = new Cookie(CookieUtils.COMMENT_AUTHOR, user.getNickname());
        Cookie commentEmail = new Cookie(CookieUtils.COMMENT_EMAIL, user.getEmail());
        Cookie commentUrl = new Cookie(CookieUtils.COMMENT_URL, user.getSite());

        commentAuthor.setPath("/");
        commentEmail.setPath("/");
        commentUrl.setPath("/");
        
        response.addCookie(commentAuthor);
        response.addCookie(commentEmail);
        response.addCookie(commentUrl);
    }
    
    public static Cookie getCookie(HttpServletRequest request, String name) {
        if (request == null) {
            return null;
        }
        Cookie[] cookies = request.getCookies();
        return getCookie(cookies, name);
    }
    
    public static Cookie getCookie(Cookie[] cookies, String name) {
        if (cookies != null) {
            for(Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    cookie.setValue(EscapeUnescapeUtils.unescape(cookie.getValue()));
                    return cookie;
                }
            }
        }
        return null;
    }
    
    public static String getCookieValue(HttpServletRequest request, String name) {
        Cookie cookie = getCookie(request, name);
        if (cookie == null) return null;
        return cookie.getValue();
    }
}