package com.ruoyi.common.filter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.*;

public class ModifyHttpServletRequestWrapper extends HttpServletRequestWrapper {
    private Map<String, String> mapCookies;
    ModifyHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
        this.mapCookies = new HashMap<>();
    }
    public void putCookie(String name, String value) {
        this.mapCookies.put(name, value);
    }
    public Cookie[] getCookies() {
        HttpServletRequest request = (HttpServletRequest) getRequest();
        Cookie[] cookies = request.getCookies();
        if (mapCookies == null || mapCookies.isEmpty()) {
            return cookies;
        }
        if (cookies == null || cookies.length == 0) {
            List<Cookie> cookieList = new LinkedList<>();
            for (Map.Entry<String, String> entry : mapCookies.entrySet()) {
                String key = entry.getKey();
                if (key != null && !"".equals(key)) {
                    cookieList.add(new Cookie(key, entry.getValue()));
                }
            }
            if (cookieList.isEmpty()) {
                return cookies;
            }
            return cookieList.toArray(new Cookie[cookieList.size()]);
        } else {
            List<Cookie> cookieList = new ArrayList<>(Arrays.asList(cookies));
            for (Map.Entry<String, String> entry : mapCookies.entrySet()) {
                String key = entry.getKey();
                if (key != null && !"".equals(key)) {
                    for (int i = 0; i < cookieList.size(); i++) {
                        if(cookieList.get(i).getName().equals(key)){
                            cookieList.remove(i);
                        }
                    }
                    cookieList.add(new Cookie(key, entry.getValue()));
                }
            }
            return cookieList.toArray(new Cookie[cookieList.size()]);
        }
    }
}
