package com.github.blindpirate.gogradle.core.dependency.tree;

import com.github.blindpirate.gogradle.core.dependency.DependencyRegistry;
import com.github.blindpirate.gogradle.core.dependency.GolangDependency;
import com.github.blindpirate.gogradle.core.dependency.ResolvedDependency;

import javax.inject.Inject;
import javax.inject.Singleton;

/**
 * Resolve all dependencies including transitive ones of a package and build a tree.
 * In this process, conflict may be resolved.
 */
@Singleton
public class DependencyTreeFactory {
    @Inject
    private DependencyRegistry registry;

    public DependencyTreeNode getTree(ResolvedDependency rootProject) {
        resolve(rootProject);
        return getSubTree(rootProject);
    }

    private DependencyTreeNode getSubTree(ResolvedDependency resolvedDependency) {
        ResolvedDependency finalDependency = registry.retrive(resolvedDependency.getName());

        DependencyTreeNode node = DependencyTreeNode.withOrignalAndFinal(resolvedDependency, finalDependency);

        for (GolangDependency dependency : finalDependency.getDependencies()) {
            node.addChild(getSubTree(dependency.resolve()));
        }
        return node;
    }

    private void resolve(ResolvedDependency resolvedDependency) {
        for (GolangDependency unresolvedDependency : resolvedDependency.getDependencies()) {
            ResolvedDependency dependency = unresolvedDependency.resolve();
            if (registry.register(dependency)) {
                // current dependency is the newest
                resolve(dependency);
            }
        }
    }
}

@@ -679,24 +679,25 @@
 otProject);%0A
+%0A
         retu
@@ -1277,217 +1277,116 @@
     
-for (GolangDependency unresolvedDependency : resolvedDependency.getDependencies()) %7B%0A            ResolvedDependency dependency = unresolvedDependency.resolve();%0A            if (registry.register(dependency)) %7B
+if (!registry.register(resolvedDependency)) %7B%0A            // current dependency is older%0A            return;
 %0A   
@@ -1386,32 +1386,34 @@
 rn;%0A        
+%7D%0A
         
 // current d
@@ -1404,48 +1404,88 @@
     
-// current dependency is the newest%0A    
+for (GolangDependency unresolvedChild : resolvedDependency.getDependencies()) %7B%0A
     
@@ -1496,17 +1496,17 @@
     
-r
+R
 esolve
-(
 d
+D
 epen
@@ -1514,24 +1514,87 @@
 ency
-);%0A            %7D
+ resolvedChild = unresolvedChild.resolve();%0A            resolve(resolvedChild);
 %0A   

add terminal condition to recursive invocation