package com.bcxin.ars.rest.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.bcxin.ars.context.SecurityContext;
import com.bcxin.ars.model.User;
import com.bcxin.ars.service.util.ArsUtil;
import com.bcxin.ars.util.redis.RedisUtil;

@Service
public class ArsRestUtil extends ArsUtil {
	
	private Logger logger = LoggerFactory.getLogger(ArsRestUtil.class);

	@Autowired
	private RedisUtil redisUtil;
	
	@Value("${login-timeout}")
	private int loginTimeout = 10;
	
	/**
	 * 获取当前登录用户
	 * @param request
	 * @return
	 */
	public User getCurrentUser(HttpServletRequest request) {
		return getCurrentUser(request, request.getParameter("sid"));
	}
	
	/**
	 * 获取当前登录用户
	 * @param request
	 * @param sessionId
	 * @return
	 */
	public User getCurrentUser(HttpServletRequest request, String sessionId) {
		User user = SecurityContext.currentUser.get();
		if(user != null) {
			setCurrentUser(request, user);
			return user;
		} else if(!StringUtils.isEmpty(sessionId)) {
			String ip = getRemoteIpAddr(request);
			String userStr = redisUtil.get(ip + "-" + sessionId);
			if(userStr != null && userStr.trim().length() > 0) {
				setCurrentUser(sessionId, userStr);
				return JSON.parseObject(userStr, User.class);
			}
		}
		return null;
	}
	
	/**
	 * 设置登录用户
	 * @param request
	 * @param user
	 */
	public void setCurrentUser(HttpServletRequest request, User user) {
		SecurityContext.currentUser.set(user);
//		String userStr = JSON.toJSONString(user);
//		String ip = getRemoteIpAddr(request);
//		setCurrentUser(ip + "-" + user.getSessionId(), userStr);
	}
	
	public void setCurrentUser(String sessionId, String userStr) {
		logger.debug("login timeout:" + loginTimeout);
		//TODO
		//shiro权限未完成，暂时去掉用户登录超时
//		redisUtil.set(sessionId, userStr, (loginTimeout * 60));
//		redisUtil.set(sessionId, userStr);
	}
	
	/**
	 * 清空当前登录用户
	 * @param request
	 */
	public void removeCurrentUser(HttpServletRequest request) {
		String ip = getRemoteIpAddr(request);
		String sid = request.getParameter("sid");
		if(redisUtil.get(ip + "-" + sid)!=null) {
			redisUtil.delete(ip + "-" + sid);
			redisUtil.delete(sid);
		}
	}
	
	/**
	 * 获取当前session
	 * @param request
	 * @return
	 */
	public HttpSession getCurrentSession(HttpServletRequest request) {
		return request.getSession();
	}
	
	/**
     * @param 获取远程IP
     * @return IP Address
     */
    public static String getRemoteIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if(ip.equals("0:0:0:0:0:0:0:1")) {
        	ip = "127.0.0.1";
        }
        return ip;
    }

}
