package com.wecloud.dispatch.extend.impl;

import com.wecloud.dispatch.ActionContext;
import com.wecloud.dispatch.extend.ActionRequest;
import com.wecloud.dispatch.extend.ArgumentBox;
import com.wecloud.dispatch.extend.MethodArgumentResolver;
import org.springframework.core.MethodParameter;

import java.util.Set;

/**
 * @author lixiaozhong
 */
public class DefaultMethodArgumentResolver implements MethodArgumentResolver {

	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		return true;
	}

	@Override
	public Object resolveArgument(ActionContext actionContext, MethodParameter parameter, ActionRequest request, ArgumentBox argumentBox) {
		// Type type = parameter.getGenericParameterType();
		Class<?> clazz = parameter.getParameterType();
		Object data = null;
		if (null != clazz) {
			if (clazz.isAssignableFrom(ActionContext.class)) {
				data = actionContext;
			} else if (clazz.isAssignableFrom(ActionRequest.class)) {
				data = request;
			} else if (clazz.isAssignableFrom(ArgumentBox.class)) {
				data = argumentBox;
			} else {
				data = argumentBox.get(clazz);
				if (null == data) {
					Set<Object> keys = argumentBox.keySet();
					if (null != keys) {
						for (Object o : keys) {
							if (o instanceof Class) {
								Class<?> classKey = (Class<?>) o;
								if (clazz.isAssignableFrom(classKey)) {
									data = argumentBox.get(o);
									break;
								}
							}
						}
					}
				}
				if (null == data) {
					data = getValue(actionContext, clazz);
				}
			}
		}
		return data;
	}

	private Object getValue(ActionContext actionContext, Class<?> clazz) {
		return actionContext.getArgumentDefaultValueBuilderRegistry().getValue(clazz);
	}
}
