package com.google.graphgeckos.dashboard.fetchers.buildbot;

import com.google.graphgeckos.dashboard.datatypes.BuildBotData;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.graphgeckos.dashboard.storage.DatastoreRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.lang.NonNull;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import java.time.Duration;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

public class BuildBotClient {

  /** Provides access to the storage. */
  @Autowired
  private DatastoreRepository datastoreRepository;

  /** Base URL of the BuildBot API. */
  private final String baseUrl;

  /** Fetcher does requests to the BuildBot API every {@code delay} seconds. */
  private final long delay;

  public BuildBotClient(@NonNull String baseUrl, long delay) {
    Objects.requireNonNull(baseUrl);
    this.baseUrl = baseUrl;
    this.delay = delay;
  }

  /** Returns request frequency in seconds. */
  public long getDelay() {
    return delay;
  }
  
  public void run(@NonNull String buildBot, int initialBuildId) {
    Objects.requireNonNull(buildBot);

    AtomicInteger buildId = new AtomicInteger(initialBuildId);

    WebClient.builder().baseUrl(baseUrl)
      .defaultHeader(HttpHeaders.CONTENT_TYPE, "application/json")
      .build()
      .get()
      .uri(String.format( "%s/builds/%d?as_text=1", buildBot, buildId.get()))
      .accept(MediaType.TEXT_PLAIN)
      .retrieve()
      .bodyToMono(String.class)
      .delaySubscription(Duration.ofSeconds(delay))
      .onErrorResume(e -> {
        System.out.println("Ignoring error: " + e.getMessage());
        return Mono.empty();
      })
      .repeat()
      .subscribe(response -> {
        if (response.isEmpty()) {
          return;
        }
        try {
          BuildBotData builder = new ObjectMapper().readValue(response, BuildBotData.class);
          datastoreRepository.updateRevisionEntry(builder);
        } catch (Exception e) {
          e.printStackTrace();
        }
        buildId.incrementAndGet();
      });
  }

}
@@ -628,23 +628,20 @@
 c.Atomic
-Integer
+Long
 ;%0A%0Apubli
@@ -1206,18 +1206,151 @@
 ay;%0A  %7D%0A
+%0A
   
+/**%0A   * @param buildBot name of the BuildBot as it is in the API (e.g %22clang-x86_64-debian-fast%22).%0A   * @param initialBuildId%0A   */
 %0A  publi
@@ -1386,19 +1386,20 @@
 ildBot, 
-int
+long
  initial
@@ -1458,23 +1458,20 @@
   Atomic
-Integer
+Long
  buildId
@@ -1487,15 +1487,12 @@
 omic
-Integer
+Long
 (ini

replace atomic integer with atomic long