package com.bcxin.ars.rest.shiro;

import com.alibaba.fastjson.JSONObject;
import com.bcxin.ars.model.User;
import com.bcxin.ars.service.util.EhcacheUtil;
import com.bcxin.ars.util.Constants;
import com.bcxin.ars.util.StringUtil;
import com.bcxin.ars.util.redis.RedisUtil;
import org.apache.shiro.web.servlet.Cookie;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;

public class SessionManager extends DefaultWebSessionManager{

    Logger logger = LoggerFactory.getLogger(SessionManager.class);
	@Autowired
	private EhcacheUtil ehcacheUtil;

	@Autowired
	private RedisUtil redisUtil;
	/**
	 * The Redis key prefix for the sessions
	 */
	private String keyPrefix = "ARS:shiro_redis_session:";
	public SessionManager() {
		super();
	}

	@Override
	protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
	    //SaaS平台传过来的sid
		String saasSID = request.getParameter("sid");
		String token = request.getParameter("token");
		String sessionID = request.getParameter("sessionID");
		//saas传过来从redis获取
		if(StringUtil.isEmpty(saasSID)){
			saasSID = token;
		}
		String sid = redisUtil.get( keyPrefix + saasSID);
		if(StringUtil.isNotEmpty(sessionID)){
			sid = ehcacheUtil.get(Constants.CACHE_PREFIX_KEY,sessionID);
		}
		if (!StringUtils.isEmpty(sid)) {
			if(request.getAttribute(Constants.SESSION_ID) != null){

			}else{
				try {
					String  userStr = ehcacheUtil.get(Constants.CACHE_PREFIX_KEY, sessionID+"_USERINFO");
					if(StringUtil.isNotEmpty(userStr)){
						request.setAttribute(Constants.LOGIN_USER, JSONObject.parseObject(userStr,User.class) );
					}
					request.setAttribute(Constants.SESSION_ID, sid);
				}catch (Exception e){
					e.printStackTrace();
				}
			}
			// 是否将sid保存到cookie，浏览器模式下使用此参数。
			if (WebUtils.isTrue(request, "__cookie")){
				HttpServletRequest rq = (HttpServletRequest)request;
				HttpServletResponse rs = (HttpServletResponse)response;
				Cookie template = getSessionIdCookie();
				Cookie cookie = new SimpleCookie(template);
				cookie.setValue(sid);
				cookie.saveTo(rq, rs);
			}
			// 设置当前session状态
			request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE,
					ShiroHttpServletRequest.URL_SESSION_ID_SOURCE); // session来源与url
			request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, sid);
			request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
			return sid;
		}else{
			return super.getSessionId(request, response);
		}
	}
}
