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

import cn.com.duiba.wolf.utils.JavaScriptUtil;
import com.alibaba.fastjson.JSONObject;
import com.duiba.tuia.youtui.web.exception.ActivityRuntimeException;
import com.duiba.tuia.youtui.web.service.TokenService;
import com.duiba.tuia.youtui.web.tool.ConsumerTokenUtil;
import com.duiba.tuia.youtui.web.tool.FileIDGenerator;
import com.duiba.tuia.youtui.web.tool.RequestLocal;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;

/** 
 * ClassName:ActivityPluginCtrl.java <br/>
 * @author  gey 
 * @date 创建时间：2016年10月13日 上午10:48:09 
 * @version 1.0 
 * @parameter  
 * @since   JDK 1.6
 */
@Controller
@RequestMapping("/token")
public class ActivityTokenCtrl {

	private static final String MULTI_DUMMY_TOKEN;
	private static final String OBFUSCATE_SCRIPT;
	@Autowired
	private TokenService tokenService;

	static {
		String content = null;
		try {
			InputStream is = ActivityTokenCtrl.class.getClassLoader().getResourceAsStream("dummy_token.js");
			content = IOUtils.toString(is, "utf-8");
		} catch (Exception e) {
			throw new ActivityRuntimeException(e);
		}
		MULTI_DUMMY_TOKEN = content;
		OBFUSCATE_SCRIPT = JavaScriptUtil.obfuscateScript(MULTI_DUMMY_TOKEN);
	}

	/**
	 * ajaxElement:(这里用一句话描述这个方法的作用). <br/>
	 * @author gey
	 * @param request
	 * @return
	 * @since JDK 1.6
	 */
	@ResponseBody
	@RequestMapping(value="/getToken",method = {RequestMethod.POST,RequestMethod.HEAD,RequestMethod.GET})
	public String getToken(HttpServletRequest request){
		JSONObject json = new JSONObject();
		Long cid= RequestLocal.get().getCid();
		if(cid==null){
			// referer没有时，提供假token
			String key = genDummyTokenKey();
			String token = genToken();
			String content = JavaScriptUtil.obfuscateScript(obfuscateToken(5, key, token))+OBFUSCATE_SCRIPT;
			json.put("token", content);
			json.put("success", true);
		} else{
			String token=getConsumerFormToken();
			String key = ConsumerTokenUtil.getScrectTokenKey();
			String content = JavaScriptUtil.obfuscateScript(obfuscateToken(5, key, token))+OBFUSCATE_SCRIPT;
			json.put("token", content);
			json.put("success", true);
		}
		return json.toJSONString();
	}



	/**
	 * 混淆token.<br>
	 * 生成一批假token，把正确的token混淆其中<br>
	 *
	 * @param count
	 * @param key
	 * @param value
	 * @return
	 */
	private String obfuscateToken(int count, String key, String value) {
		StringBuilder stringBuilder = new StringBuilder();
		int index = RandomUtils.nextInt(count);
		for (int i = 0; i < count; i++) {
			stringBuilder.append("window['").append(genDummyTokenKey()).append("']=\"").append(genToken()).append("\";");
			if (index == i) {
				stringBuilder.append("window['").append(key).append("']=\"").append(value).append("\";");
			}
		}
		// 前端批量生成token js
//		if (StringUtils.isNotBlank(MULTI_DUMMY_TOKEN)) {
//			stringBuilder.append(MULTI_DUMMY_TOKEN);
//		}
		return stringBuilder.toString();
	}

	private String genDummyTokenKey() {
		String hash = DigestUtils.md5Hex(String.valueOf(RandomUtils.nextInt(10000000)));
		return hash.substring(hash.length() - 8);
	}

	private String genToken() {
		int length = RandomUtils.nextInt(5) + 5;
		return FileIDGenerator.getRandomString(length);
	}

	/**
	 *
	 * @return String
	 */
	private String getConsumerFormToken() {
		return tokenService.getConsumerTokenFromCache(RequestLocal.get().getCid());
	}

}
