package com.sptg.common.core.util;

import com.sptg.common.core.constant.CommonConstant;
import com.sptg.common.core.constant.OperationConstant;
import com.sptg.common.core.constant.SymbolConstant;

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;

/**
 * title: CookieUtils
 * package: com.sptg.common.core.util
 * description: Cookie工具类
 *                  
 *                
 */
public final class CookieUtils {


    /**
     * 得到Cookie的值, 不编码
     * @param cookieName Cookie名称
     * @return String
     *                  
     *                       
     */
    public static String getCookieValue(String cookieName) {
        return getCookieValue(cookieName, false);
    }

    /**
     * 得到Cookie的值
     * @param cookieName Cookie名称
     * @return String
     *                  
     *                       
     */
    public static String getCookieValue(String cookieName, boolean isDecoder) {
        HttpServletRequest request = WebUtils.getHttpServletRequest();
        Cookie[] cookieList = request.getCookies();
        if (cookieList == null || cookieName == null) {
            return null;
        }
        String retValue = null;
        try {
            for(Cookie cookie : cookieList){
                if (cookie.getName().equals(cookieName)){
                    if (isDecoder){
                        retValue = URLDecoder.decode(cookie.getValue(), CommonConstant.UTF_8);
                    }else {
                        retValue = cookie.getValue();
                    }
                    break;
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return retValue;
    }

    /**
     * 得到Cookie的值
     * @param cookieName Cookie名称
     * @return String
     *                  
     *                       
     */
    public static String getCookieValue(String cookieName, String encodeString) {
        HttpServletRequest request = WebUtils.getHttpServletRequest();
        Cookie[] cookieList = request.getCookies();
        if (cookieList == null || cookieName == null) {
            return null;
        }
        String retValue = null;
        try {
            for (Cookie cookie:cookieList){
                if (cookie.getName().equals(cookieName)){
                    retValue = URLDecoder.decode(cookie.getValue(), encodeString);
                    break;
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return retValue;
    }

    /**
     * 设置Cookie的值 不设置生效时间默认浏览器关闭即失效,也不编码
     */
    public static void setCookie(String cookieName, String cookieValue) {
        setCookie(cookieName, cookieValue, OperationConstant.MINUS_ONE);
    }

    /**
     * 设置Cookie的值 在指定时间内生效,但不编码
     */
    public static void setCookie(String cookieName, String cookieValue, int cookieMaxAge) {
        setCookie(cookieName, cookieValue, cookieMaxAge, false);
    }

    /**
     * 设置Cookie的值 不设置生效时间,但编码
     */
    public static void setCookie(String cookieName,String cookieValue, boolean isEncode) {
        setCookie(cookieName, cookieValue, OperationConstant.MINUS_ONE, isEncode);
    }

    /**
     * 设置Cookie的值 在指定时间内生效, 编码参数
     */
    public static void setCookie(String cookieName,String cookieValue, int cookieMaxAge, boolean isEncode) {
        doSetCookie(cookieName, cookieValue, cookieMaxAge, isEncode);
    }

    /**
     * 设置Cookie的值 在指定时间内生效, 编码参数(指定编码)
     */
    public static void setCookie(String cookieName,String cookieValue, int cookieMaxAge, String encodeString) {
        doSetCookie(cookieName, cookieValue, cookieMaxAge, encodeString);
    }

    /**
     * 删除Cookie带cookie域名
     */
    public static void deleteCookie(String cookieName) {
        doSetCookie(cookieName, CommonConstant.EMPTY, OperationConstant.MINUS_ONE, false);
    }

    /**
     * 设置Cookie的值，并使其在指定时间内生效
     * @param cookieMaxAge cookie生效的最大秒数
     *                  
     *                       
     */
    private static void doSetCookie(String cookieName, String cookieValue, int cookieMaxAge, boolean isEncode) {
        HttpServletRequest request = WebUtils.getHttpServletRequest();
        HttpServletResponse response = WebUtils.getHttpServletResponse();
        try {
            if (cookieValue == null) {
                cookieValue = CommonConstant.EMPTY;
            } else if (isEncode) {
                cookieValue = URLEncoder.encode(cookieValue, CommonConstant.UTF_8);
            }
            Cookie cookie = new Cookie(cookieName, cookieValue);
            if (cookieMaxAge > OperationConstant.ZERO) {
                cookie.setMaxAge(cookieMaxAge);
            }
            // 设置域名的cookie
            if (null != request) {
                String domainName = getDomainName(request);
                if (!CommonConstant.LOCALHOST.equals(domainName)) {
                    cookie.setDomain(domainName);
                }
            }
            cookie.setPath(SymbolConstant.BACK_SLASH);
            response.addCookie(cookie);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置Cookie的值，并使其在指定时间内生效
     * @param cookieMaxAge cookie生效的最大秒数
     *                  
     *                       
     */
    private static void doSetCookie(String cookieName, String cookieValue, int cookieMaxAge, String encodeString) {
        HttpServletRequest request = WebUtils.getHttpServletRequest();
        try {
            if (cookieValue == null) {
                cookieValue = CommonConstant.EMPTY;
            } else {
                cookieValue = URLEncoder.encode(cookieValue, encodeString);
            }
            Cookie cookie = new Cookie(cookieName, cookieValue);
            if (cookieMaxAge > OperationConstant.ZERO) {
                cookie.setMaxAge(cookieMaxAge);
            }
            if (null != request) {
                // 设置域名的cookie
                String domainName = getDomainName(request);
                if (!CommonConstant.LOCALHOST.equals(domainName)) {
                    cookie.setDomain(domainName);
                }
            }
            cookie.setPath(SymbolConstant.BACK_SLASH);
            HttpServletResponse response = WebUtils.getHttpServletResponse();
            response.addCookie(cookie);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 得到cookie的域名
     */
    private static String getDomainName(HttpServletRequest request) {
        StringBuffer url = request.getRequestURL();
        //  删除 http://
        url.delete(OperationConstant.ZERO,url.indexOf(SymbolConstant.DOUBLE_SLASH) + OperationConstant.TWO);
        int index = url.indexOf(SymbolConstant.COLON);
        if(index > OperationConstant.MINUS_ONE){
            //  删除端口及后面的路径
            url.delete(index, url.length());
        }else {
            //  删除多余的路径
            url.delete(url.length() - request.getRequestURI().length(), url.length());
        }
        return url.toString();
    }



}
