/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved. <a>http://www.crunii.com</a>
 */
package com.crunii.micro.web.mvc;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.MethodParameter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * @author 田平 create 2016年1月19日下午2:06:32
 */
public class SessionScopeMAR implements HandlerMethodArgumentResolver {
	private static final Log log = LogFactory.getLog(SessionScopeMAR.class);

	/**
	 * @see org.springframework.web.method.support.HandlerMethodArgumentResolver#supportsParameter(org.springframework.core.MethodParameter)
	 */
	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		if (parameter.hasParameterAnnotation(SessionScope.class)) {
			return true;
		} else if (parameter.getMethodAnnotation(SessionScope.class) != null) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * @see org.springframework.web.method.support.HandlerMethodArgumentResolver#resolveArgument(org.springframework.core.MethodParameter, org.springframework.web.method.support.ModelAndViewContainer, org.springframework.web.context.request.NativeWebRequest, org.springframework.web.bind.support.WebDataBinderFactory)
	 */
	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
		String annoVal = null;
		if (parameter.getParameterAnnotation(SessionScope.class) != null) {
			annoVal = parameter.getParameterAnnotation(SessionScope.class).value();
		} else if (parameter.getMethodAnnotation(SessionScope.class) != null) {
			annoVal = parameter.getMethodAnnotation(SessionScope.class) != null ? parameter.getMethodAnnotation(SessionScope.class).value() : null;
		}
		if (StringUtils.hasText(annoVal)) {
			log.debug("sessionId:" + webRequest.getSessionId());
			Object attr = webRequest.getAttribute(annoVal, RequestAttributes.SCOPE_SESSION);
			log.debug("SessionAttr name:" + annoVal + ",value:" + attr);
			//取消兼容老项目的登陆用户
			/*if (attr != null) {
				return JsonUtil.jsonToObject(attr.toString(), parameter.getParameterType());
			}*/
			return attr;
		} else {
			return null;
		}
	}
}
