package io.micronaut.inject.qualifiers;
import io.micronaut.core.annotation.Internal;
import io.micronaut.core.reflect.ClassUtils;
import io.micronaut.core.util.CollectionUtils;
import io.micronaut.core.util.StreamUtils;
import io.micronaut.inject.BeanType;
import org.slf4j.Logger;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Internal
public class ClosestTypeArgumentQualifier<T> extends TypeArgumentQualifier<T> {
private static final Logger LOG = ClassUtils.getLogger(ClosestTypeArgumentQualifier.class);
private final List<Class>[] hierarchies;
ClosestTypeArgumentQualifier(Class... typeArguments) {
super(typeArguments);
this.hierarchies = new List[typeArguments.length];
for (int i = 0 ; i < typeArguments.length; i++) {
hierarchies[i] = ClassUtils.resolveHierarchy(typeArguments[i]);
}
}
@Override
public <BT extends BeanType<T>> Stream<BT> reduce(Class<T> beanType, Stream<BT> candidates) {
return candidates
.filter(candidate -> beanType.isAssignableFrom(candidate.getBeanType()))
.map(candidate -> {
List<Class> typeArguments = getTypeArguments(beanType, candidate);
int result = compare(typeArguments);
if (LOG.isTraceEnabled() && result < 0) {
LOG.trace("Bean type {} is not compatible with candidate generic types [{}] of candidate {}", beanType, CollectionUtils.toString(typeArguments), candidate);
}
return new AbstractMap.SimpleEntry<>(candidate, result);
})
.filter(entry -> entry.getValue() > -1)
.collect(StreamUtils.minAll(
Comparator.comparingInt(Map.Entry::getValue),
Collectors.toList())
)
.stream()
.map(Map.Entry::getKey);
}
protected int compare(List<Class> classesToCompare) {
final Class[] typeArguments = getTypeArguments();
if (classesToCompare.isEmpty() && typeArguments.length == 0) {
return 0;
} else if (classesToCompare.size() != typeArguments.length) {
return -1;
} else {
int comparison = 0;
for (int i = 0; i < classesToCompare.size(); i++) {
if (typeArguments[i] == Object.class) {
continue;
}
Class left = classesToCompare.get(i);
List<Class> hierarchy = hierarchies[i];
int index = hierarchy.indexOf(left);
if (index == -1) {
comparison = -1;
break;
}
comparison = comparison + index;
}
return comparison;
}
}
}