package com.duiba.tuia.youtui.web.tool;

import cn.com.duiba.wolf.utils.BlowfishUtils;
import com.duiba.tuia.youtui.web.exception.ActivityRuntimeException;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;
import java.util.Random;

/** 
 * ClassName:ConsumerTokenUtil.java <br/>
 * @author  gey 
 * @date 创建时间：2016年11月23日 下午4:38:55 
 * @version 1.0 
 * @parameter  
 * @since   JDK 1.6
 */
public class ConsumerTokenUtil {

	private static final Logger log = LoggerFactory.getLogger(ConsumerTokenUtil.class);

	public static final String TEMP_TOKEN = "oVb7vvJgbY1nFxsV";

	public ConsumerTokenUtil() {
		// toolbox 有引用此构造方法，不可私有化
	}

	/**
	 *
	 * getScrectTokenKey:(这里用一句话描述这个方法的作用). <br/>
	 * @return
	 * @since JDK 1.6
	 */
	public static String getScrectTokenKey(){
		String key="uiiosaidnbua";

		String c = RequestLocal.get().getTokenId();
		if (c == null) {
			log.warn("用户token不存在，os={}, ua={}, userAgent={}", RequestLocal.get().getOs(),
					RequestTool.getUA(RequestTool.getUserAgent(RequestLocal.get().getRequest())),
					RequestTool.getUserAgent(RequestLocal.get().getRequest()));
			return key;
		}
		try {
			String md5 = MD5.md5(c);
			key=md5.substring(md5.length()-8);
		} catch (Exception e) {
			throw new ActivityRuntimeException(e);
		}
		return key;
	}

	/**
	 * getTempToken:(获取临时token). <br/>
	 *
	 * @return
	 * @since JDK 1.6
	 */
	public static String getTempToken() {
		return TEMP_TOKEN;
	}

	/**
	 * 获取从cookie中解密后取出的JSONObject对象
	 * @param request
	 * @param key
	 * @return
	 */
	public static String getCookieForTokenId(HttpServletRequest request,String key){
		Cookie cookie = getCookieByName(request,"dbtdtkid");
		if(null != cookie){
			return BlowfishUtils.decryptBlowfish(cookie.getValue(), key);
		}
		return null;
	}

	/**
	 * 加入cookie。
	 * @param response
	 * @param appKey
	 * @param key
	 */
	public static void addCookieForTokenId(HttpServletResponse response,String tokenId,String key){
		String envalue=BlowfishUtils.encryptBlowfish(tokenId, key);
		addCookie(response, "dbtdtkid", envalue);
	}

	/**
	 * 根据名字获取cookie
	 * @param request
	 * @param name
	 * @return
	 */
	public static Cookie getCookieByName(HttpServletRequest request, String name) {
		Map<String, Cookie> cookieMap = readCookieMap(request);
		if (cookieMap.containsKey(name)) {
			return cookieMap.get(name);
		} else {
			return null;
		}
	}

	/**
	 * 将cookie封装到Map里面
	 * @param request
	 * @return
	 */
	public static Map<String, Cookie> readCookieMap(HttpServletRequest request) {
		Map<String, Cookie> cookieMap = Maps.newHashMap();
		Cookie[] cookies = request.getCookies();
		if (null != cookies) {
			for (Cookie cookie : cookies) {
				cookieMap.put(cookie.getName(), cookie);
			}
		}
		return cookieMap;
	}

	/**
	 * 根据appKey、dateTime和1-1000随机数生成唯一的TokenId
	 * @param appKey
	 * @param key
	 * @return
	 */
	public static String generalTokenId(String appKey){
		Random ra =new Random();
		int a = ra.nextInt(1000)+1;
		long dateTime = new Date().getTime();
		return appKey +"-"+ dateTime + a;
	}

	/**
	 * 设置cookie
	 * @param response
	 * @param name	cookie名字
	 * @param value   cookie值
	 * @param maxAge  cookie生命周期 以秒为单位
	 */
	public static void addCookie(HttpServletResponse response, String name, String value) {
		Cookie cookie = new Cookie(name, value);
		cookie.setPath("/");
		response.addCookie(cookie);
	}
}

