package com.cirle.scientific.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * @author DeMin
 * @date 2022年06月13日 23:17
 */
public class CookieUtil {


    public static void setMainCookie(HttpServletResponse response, String memToken, String memCard, String domain) {

        addValue2Cookie(response, domain, "/", "memCard", memCard, 1);

        addValue2Cookie(response, domain, "/", "memToken", memToken,1);

//        if (member.getMemMobile() != null && !"".equals(member.getMemMobile())) {
//            addValue2Cookie(response, domain, "/", "bindMobile", "1", LoginConsts.M_LOGIN_COOKIE_EXPIRE);
//        }
    }

    /**
     * 将值存入cookie
     *
     * @param response
     * @param key
     * @param val
     */
    public static void addValue2Cookie(HttpServletResponse response, String domain, String path, String key, String val,
                                int time) {
        if (val == null || "".equals(val)) {
            return;
        }
        try {
            val = URLEncoder.encode(val, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.addHeader("P3P", "CP=CAO PSA OUR");
        Cookie c = new Cookie(key, val);
        c.setDomain(domain);
        c.setMaxAge(time);
        c.setPath(path);
        response.addCookie(c);
    }


    /**
     * 清除cookie
     * @param response
     */
    public static void clearCookies(HttpServletResponse response, String domain, String path, String key) {
        Cookie c = new Cookie(key, null);
        c.setDomain(domain);
        c.setMaxAge(0);
        c.setPath(path);
        response.addCookie(c);
    }

    public static String getValueByCookie(HttpServletRequest request, String key) {
        String cookievalue = null;
        Cookie[] cookies = request.getCookies();
        if (null != cookies && cookies.length != 0) {
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                if (cookie.getName().equals(key)) {
                    // String value = cookie.getValue();
                    try {
                        cookievalue = URLDecoder.decode(cookie.getValue(), "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    // cookievalue = value;
                    break;
                }
            }
        }
        return cookievalue;
    }
}
