package com.microservices.common.core.utils;

import java.util.HashMap;

public class CookieUtil {


    public static HashMap<String, String> getCookieMap(String cookie) {
        HashMap<String, String> map = new HashMap<>();
        if (cookie != null) {
            String[] cookies = cookie.split(";");
            for (String cookieStr : cookies) {
                String[] cookieArr = cookieStr.split("=");
                String key = cookieArr[0].trim();
                String value = cookieArr[1].trim();
                map.put(key, value);
            }
        }
        return map;
    }

    public static String getCookieValue(String cookie, String key) {
        HashMap<String, String> map = getCookieMap(cookie);
        return map.get(key);
    }

    public static String removeCookieKey(String cookie, String key) {
        HashMap<String, String> map = getCookieMap(cookie);
        map.remove(key);
        return genCookieStr(map);
    }

    private static String genCookieStr(HashMap<String, String> cookieMap) {
        StringBuilder stringBuilder = new StringBuilder();
        for (String key : cookieMap.keySet()) {
            stringBuilder.append(key).append("=").append(cookieMap.get(key)).append(";");
        }
        return stringBuilder.toString();
    }
}
