package com.huigou.uasp.resolver;

import com.huigou.context.ContextUtil;
import com.huigou.context.ThreadLocalUtil;
import com.huigou.util.Constants;
import com.huigou.util.SDO;
import com.huigou.util.StringUtil;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * 绑定SDO到springmvc控制器的方法参数。
 *
 * @author yonghuan
 */
public class SdoHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return SDO.class.isAssignableFrom(parameter.getParameterType());
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        return getSDO(webRequest.getNativeRequest(HttpServletRequest.class));
    }

    protected SDO getSDO(HttpServletRequest request) {
        SDO sdo;
        if (ContextUtil.isAppRequest()) {
            sdo = (SDO) request.getAttribute(Constants.SDO);
        } else {
            sdo = new SDO(true);
            Enumeration<?> em = request.getParameterNames();
            while (em.hasMoreElements()) {
                String key = (String) em.nextElement();
                String[] values = request.getParameterValues(key);
                if (values != null && values.length > 0) {
                    if (values.length == 1) {
                        sdo.putProperty(key, StringUtil.decode(values[0]));
                    } else {
                        sdo.putProperty(key, values);
                    }
                }
            }
        }
        sdo.setOperator(ContextUtil.findOperator());
        ThreadLocalUtil.putVariable(Constants.SDO, sdo);
        return sdo;
    }
}
