package com.wecloud.netty.dispatch.registry;

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

import java.util.LinkedList;
import java.util.List;

/**
 * @author lixiaozhong
 */
public class MethodArgumentResolverRegistry {

	List<MethodArgumentResolver> list = new LinkedList<>();

	public void add(MethodArgumentResolver mar) {
		list.add(mar);
	}

	public boolean supportsParameter(MethodParameter parameter) {
		return (getArgumentResolver(parameter) != null);
	}

	public Object resolveArgument(ActionContext actionContext, MethodParameter parameter, ActionRequest request, ArgumentBox argumentBox) {
		MethodArgumentResolver resolver = getArgumentResolver(parameter);
		if (resolver == null) {
			throw new IllegalArgumentException("Unknown parameter type [" + parameter.getParameterType().getName() + "]");
		}
		return resolver.resolveArgument(actionContext, parameter, request, argumentBox);
	}

	private MethodArgumentResolver getArgumentResolver(MethodParameter parameter) {
		MethodArgumentResolver result = null;
		for (MethodArgumentResolver methodArgumentResolver : this.list) {
			if (methodArgumentResolver.supportsParameter(parameter)) {
				result = methodArgumentResolver;
				break;
			}
		}
		return result;
	}
}
