package com.hubspot.blazar.listener;

import com.hubspot.blazar.base.DependencyGraph;
import com.hubspot.blazar.base.ModuleBuild;
import com.hubspot.blazar.base.RepositoryBuild;
import com.hubspot.blazar.base.listener.ModuleBuildListener;
import com.hubspot.blazar.data.service.RepositoryBuildService;
import com.hubspot.blazar.util.ModuleBuildLauncher;

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

@Singleton
public class QueuedModuleBuildListener implements ModuleBuildListener {
  private final RepositoryBuildService repositoryBuildService;
  private final ModuleBuildLauncher moduleBuildLauncher;

  @Inject
  public QueuedModuleBuildListener(RepositoryBuildService repositoryBuildService,
                                   ModuleBuildLauncher moduleBuildLauncher) {
    this.repositoryBuildService = repositoryBuildService;
    this.moduleBuildLauncher = moduleBuildLauncher;
  }

  @Override
  public void buildChanged(ModuleBuild build) throws Exception {
    RepositoryBuild repositoryBuild = repositoryBuildService.get(build.getRepoBuildId()).get();
    DependencyGraph dependencyGraph = repositoryBuild.getDependencyGraph().get();

    if (dependencyGraph.incomingVertices(build.getModuleId()).isEmpty()) {
      moduleBuildLauncher.launch(repositoryBuild, build);
    }
  }
}

@@ -27,24 +27,63 @@
 .listener;%0A%0A
+import com.google.common.collect.Sets;%0A
 import com.h
@@ -118,16 +118,16 @@
 yGraph;%0A
-
 import c
@@ -271,16 +271,75 @@
 stener;%0A
+import com.hubspot.blazar.data.service.ModuleBuildService;%0A
 import c
@@ -504,16 +504,64 @@
 ngleton;
+%0Aimport java.util.HashSet;%0Aimport java.util.Set;
 %0A%0A@Singl
@@ -700,16 +700,71 @@
 ervice;%0A
+  private final ModuleBuildService moduleBuildService;%0A
   privat
@@ -905,16 +905,90 @@
 ervice,%0A
+                                   ModuleBuildService moduleBuildService,%0A
         
@@ -1115,16 +1115,66 @@
 ervice;%0A
+    this.moduleBuildService = moduleBuildService;%0A
     this
@@ -1478,16 +1478,17 @@
 get();%0A%0A
+%0A
     if (
@@ -1616,13 +1616,617 @@
 d);%0A
-
     %7D
+ else %7B%0A      Set%3CInteger%3E buildingModules = extractModuleIds(moduleBuildService.getByRepositoryBuild(build.getRepoBuildId()));%0A      Set%3CInteger%3E upstreamModules = dependencyGraph.incomingVertices(build.getModuleId());%0A%0A      if (Sets.intersection(buildingModules, upstreamModules).isEmpty()) %7B%0A        moduleBuildLauncher.launch(repositoryBuild, build);%0A      %7D%0A    %7D%0A  %7D%0A%0A  private static Set%3CInteger%3E extractModuleIds(Set%3CModuleBuild%3E builds) %7B%0A    Set%3CInteger%3E moduleIds = new HashSet%3C%3E();%0A    for (ModuleBuild build : builds) %7B%0A      moduleIds.add(build.getModuleId());%0A    %7D%0A%0A    return moduleIds;
 %0A  %7D

Fix bug with launching queued module builds