package org.wildfly.swarm.cdi;

import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;

import javax.enterprise.event.Observes;
import javax.enterprise.inject.spi.AfterBeanDiscovery;
import javax.enterprise.inject.spi.Extension;
import javax.enterprise.inject.spi.ProcessAnnotatedType;
import javax.enterprise.inject.spi.WithAnnotations;
import javax.enterprise.inject.spi.builder.BeanConfigurator;
import javax.inject.Singleton;

import org.wildfly.swarm.spi.api.DefaultFraction;
import org.wildfly.swarm.spi.api.Fraction;

/**
 * @author Ken Finnigan
 */
public class InstallUserFractionExtension implements Extension {
    public static Map<Class<?>, Fraction> userFractions = new HashMap<>();

    <T> void processAnnotatedType(@Observes @WithAnnotations(DefaultFraction.class) ProcessAnnotatedType<T> pat) {
        if (userFractions.containsKey(pat.getAnnotatedType().getJavaClass())) {
            pat.veto();
        }
    }

    void afterBeanDiscovery(@Observes AfterBeanDiscovery abd) {
        for (Fraction fraction : userFractions.values()) {
            BeanConfigurator<Object> configurator = abd.addBean()
                    .addType(fraction.getClass())
                    .addType(Fraction.class)
                    .scope(Singleton.class)
                    .produceWith(() -> fraction);

            for(Annotation annotation: fraction.getClass().getAnnotations()) {
                configurator.qualifiers(annotation);
            }
        }
    }
}

@@ -1351,19 +1351,150 @@
         
-for
+Annotation%5B%5D qualifiers = new Annotation%5Bfraction.getClass().getAnnotations().length - 1%5D;%0A            int index = 0;%0A            for 
 (Annotat
@@ -1507,16 +1507,17 @@
 notation
+ 
 : fracti
@@ -1570,32 +1570,116 @@
     
-configurator.qualifiers(
+if (!annotation.annotationType().equals(DefaultFraction.class)) %7B%0A                    qualifiers%5Bindex++%5D = 
 anno
@@ -1684,19 +1684,22 @@
 notation
-)
 ;%0A
+    
         
@@ -1700,24 +1700,87 @@
           %7D%0A
+            %7D%0A            configurator.qualifiers(qualifiers);%0A
         %7D%0A  

Fix problem of WildFly Extension not being found when Fraction added by Swarm.fraction()