package com.wizzardo.http.framework.di;

import com.wizzardo.tools.cache.Cache;
import com.wizzardo.tools.reflection.FieldReflection;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wizzardo on 05.05.15.
 */
public abstract class Dependency<T> {
    protected static Cache<Class, List<FieldReflection>> dependencies = new Cache<>(0, clazz -> {
        List<FieldReflection> l = new ArrayList<>();
        while (clazz != null) {
            for (Field f : clazz.getDeclaredFields()) {
                int mod = f.getType().getModifiers();
                if (Modifier.isFinal(mod) || f.getType().isPrimitive())
                    continue;
                if (f.getType().getAnnotation(Injectable.class) != null
                        || Modifier.isAbstract(mod)
                        || Modifier.isInterface(mod)) {
                    l.add(new FieldReflection(f, true));
                } else
                    for (Class i : f.getType().getInterfaces()) {
                        if (i.getAnnotation(Injectable.class) != null) {
                            l.add(new FieldReflection(f, true));
                            break;
                        }
                    }
            }
            clazz = clazz.getSuperclass();
        }
        return l;
    });

    public abstract T get();

    protected void injectDependencies(Object ob) {
        for (FieldReflection f : dependencies.get(ob.getClass())) {
            f.setObject(ob, DependencyFactory.getDependency(f.getField().getType()));
        }
    }
}

@@ -223,16 +223,43 @@
 ayList;%0A
+import java.util.Iterator;%0A
 import j
@@ -1469,24 +1469,42 @@
 bject ob) %7B%0A
+        try %7B%0A    
         for 
@@ -1555,24 +1555,28 @@
 Class())) %7B%0A
+    
             
@@ -1645,24 +1645,702 @@
 etType()));%0A
+            %7D%0A        %7D catch (Exception e) %7B%0A            synchronized (ob.getClass()) %7B%0A                List%3CFieldReflection%3E list = new ArrayList%3C%3E(dependencies.get(ob.getClass()));%0A                Iterator%3CFieldReflection%3E iterator = list.iterator();%0A%0A                while (iterator.hasNext()) %7B%0A                    FieldReflection f = iterator.next();%0A                    try %7B%0A                        f.setObject(ob, DependencyFactory.getDependency(f.getField().getType()));%0A                    %7D catch (Exception ex) %7B%0A                        iterator.remove();%0A                    %7D%0A                %7D%0A                dependencies.put(ob.getClass(), list);%0A            %7D%0A
         %7D%0A  

fix dependencies