package com.community.commom.utils;


import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * describe: cookie 历史记录
 * creat_user: gengxiang
 * creat_time: 2017/12/25 9:05
 * version V1.0
 **/
public class CookieUtil {

    /**
     * 获取所有的历史记录
     *
     * @param cookies 所有的cookie
     * @param type    获取的cookie类型
     * @return java.util.List<java.lang.String>
     * @author gengxiang
     * @date 2017/12/25 9:19
     */
    public static List<String> getAll(Cookie[] cookies, String type) {
        List<String> result = new ArrayList<>();
        Map<String, Cookie> cookieMap = toCookieMap(cookies);
        Cookie cookie = cookieMap.get(type);
        if (cookie != null) {
            String value = cookie.getValue();
            if (StringUtils.hasText(value)){
                String[] values = value.split("#");
                for (int i = 0; i < values.length; i++) {
                    result.add(values[i]);
                }
            }
        }
        return result;
    }

    /**
     * 设置cookie
     * @author gengxiang
     * @date 2017/12/25 10:08
     * @param cookies cookie array
     * @param type  cookie name
     * @param value cookie value
     * @return javax.servlet.http.Cookie
     */
    public static Cookie setCookie(Cookie[] cookies, String type, String value) {

        Map<String, Cookie> cookieMap = toCookieMap(cookies);
        Cookie cookie = cookieMap.get(type);
        if (cookie != null && StringUtils.hasText(cookie.getValue())
                && !(cookie.getValue().startsWith(value) || cookie.getValue().contains("#"+value))){
            //cookie值中“#”出现的次数
            int times = appearTimes(cookie.getValue(), "#");
            //10个值有9个“#”，小于9直接保存到cookie
            if(times < 9){
                cookie.setValue(value+"#"+cookie.getValue());
                cookie.setMaxAge(60*60*24*30);
                cookie.setPath("/");
            }else {
                String oldValue = cookie.getValue();
                //截取最新的9个值
                String newValue = oldValue.substring(0, oldValue.lastIndexOf("#"));
                cookie.setValue(value + "#" + newValue);
                cookie.setMaxAge(60*60*24*30);
                cookie.setPath("/");
            }
        }else if (cookie == null || !StringUtils.hasText(cookie.getValue())){
            cookie = new Cookie(type, value);
            cookie.setMaxAge(60*60*24*30);
            cookie.setPath("/");
            cookie.setHttpOnly(true);
        }
        return cookie;
    }

    /**
     * 删除 cookie
     * @author gengxiang
     * @date 2017/12/25 10:17
     * @param cookies cookie array
     * @param type  cookie name
     * @return javax.servlet.http.Cookie
     */
    public static Cookie delCookie(Cookie[] cookies, String type){
        Map<String, Cookie> cookieMap = toCookieMap(cookies);
        Cookie cookie = cookieMap.get(type);
        if (cookie != null){
            cookie.setValue(null);
            cookie.setMaxAge(0);
            cookie.setPath("/");
        }
        return cookie;
    }


    /**
     * cookie array to map
     * @author gengxiang
     * @date 2017/12/25 10:10
     * @param cookies
     * @return java.util.Map<java.lang.String,javax.servlet.http.Cookie>
     */
    public static Map<String, Cookie> toCookieMap(Cookie[] cookies) {
        Map<String, Cookie> result = new HashMap<>();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                result.put(cookie.getName(), cookie);
            }
        }
        return result;
    }


    /**
     * 获取指定字符串出现的次数
     *   
     * @author xrq  
     * @date 2017/12/25 15:16
     * @param srcText 源字符串
     * @param findText 要查找的字符串
     * @return int  
     */ 
    public static int appearTimes(String srcText, String findText) {
        int count = 0;
        Pattern p = Pattern.compile(findText);
        Matcher m = p.matcher(srcText);
        while (m.find()) {
            count++;
        }
        return count;
    }
}
