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

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.duiba.tuia.youtui.web.constant.CookieDefine;
import com.duiba.tuia.youtui.web.constant.ErrorCode;
import com.duiba.tuia.youtui.web.exception.ActivityException;
import com.duiba.tuia.youtui.web.model.ConsumerAction;

/** 
 * 手势行为的判断工具
 * 
 * ClassName:BehaviorSwipeUtils.java <br/>
 * @author  gey 
 * @date 创建时间：2016年11月18日 上午9:42:41 
 * @version 1.0 
 * @parameter  
 * @since   JDK 1.6
 */
public class BehaviorSwipeUtils {
	
	private static  Logger log = LoggerFactory.getLogger(BehaviorSwipeUtils.class);
	
	private static final String STRING_NULL = "null";
	private static final String FORM_PARAMS_KEY = "dba";
	//手势不存在
	public static final int SWIPE_NOT_EXIST = 0;
	//手势存在
	public static final int SWIPE_EXIST = 1;
	//验证出错
	public static final int SWIPE_ERROR = 2;
	//不需要验证手势
	public static final int SWIPE_SKIP = 3;
	
	
	private BehaviorSwipeUtils(){
	    
	}
	
	/**
	 * 判断是否有手势
	 * @param request
	 * @param itemKey
	 * @param consumer
	 * @param app
	 * @return
	 */
	public static int swipeCheck(HttpServletRequest request){
		String ua = request.getHeader("User-Agent");
		if (StringUtils.isBlank(ua)) {
			return SWIPE_SKIP;
		}
		
		ua = ua.toLowerCase();
		if (ua.contains("iphone") || ua.contains("ipad") || ua.contains("android")) {
			try {
				List<ConsumerAction> actions = parse(request);
				return actions.isEmpty() ? SWIPE_NOT_EXIST : SWIPE_EXIST;
			} catch (Exception e) {
				log.error("swipeCheck error",e);
				return SWIPE_ERROR;
			}
		}
		
		return SWIPE_SKIP;
	}
	
	@SuppressWarnings("unchecked")
    private static List<ConsumerAction> parse(HttpServletRequest request) throws ActivityException{
		String key=RequestTool.getCookie(request, CookieDefine.ConsumerLoginCookie);
		String value=request.getParameter(FORM_PARAMS_KEY);
		if (StringUtils.isBlank(value) || value.equals(STRING_NULL)) {
			return ListUtils.EMPTY_LIST;
		}
		value=BehaviorCipher.decode(value, key);
		if(value==null){
			throw new ActivityException(ErrorCode.E0000002);
		}
		List<ConsumerAction> list=new ArrayList<>();
		JSONArray array=JSON.parseArray(value);
		for(int i=0;i<array.size();i++){
			JSONObject o=array.getJSONObject(i);
			ConsumerAction ca=new ConsumerAction();
			ca.setReferer(o.getString("referer"));
			ca.setTime(new Date(o.getLong("time")));
			ca.setType(o.getString("type"));
			ca.setUrl(o.getString("url"));
			list.add(ca);
		}
		return list;
	}
}
