package com.armundia.core.websocket.annotation;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.HashMap;
import java.util.Map;

import com.armundia.core.websocket.pojo.WebSocketAnnotatedMethod;

/**
 * TODO: that should help to get automatically the annotation @On on the websocket method.
 * the problem is that the @RequestScoped cannot be caught because it is instanciated on an HTTP call
 */
public class WebSocketAnnotationScanner {
	private WebSocketAnnotationScanner() {
		
	}
	
    public static Map<String, WebSocketAnnotatedMethod> getOnMessages() {
    	Map<String, WebSocketAnnotatedMethod> onMessageMethods = new HashMap<>();
    	
        PackageUtil.getClasses("com.armundia").forEach(clazz -> {
            for (Method method : clazz.getDeclaredMethods()) {
                if (method.isAnnotationPresent(On.class)) {
                    On annotation = method.getAnnotation(On.class);
                    String value = annotation.value();
                    System.out.println("Found @On in class: " + clazz.getName() + ", method: " + method.getName() + ", value: " + value);
                    
                    Parameter[] parameters = method.getParameters();
                    Class<?>[] argumentsType = null;
					if (parameters.length == 1) {
						argumentsType = new Class<?>[1];
						argumentsType[0] = parameters[0].getType();
					} else if (parameters.length == 2) {
						argumentsType = new Class<?>[2];
                    	argumentsType[0] = parameters[0].getType();
                    	argumentsType[1] = parameters[1].getType();
                    }
                    
                    onMessageMethods.put(value, new WebSocketAnnotatedMethod(clazz, method, argumentsType));
                }
            }
        });
        
        return onMessageMethods;
    }
}



