package zielu.gittoolbox.util;

import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import git4idea.repo.GitRepository;
import git4idea.util.GitUIUtil;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicBoolean;
import jodd.util.StringBand;
import zielu.gittoolbox.compat.Notifier;

public class FetchResultsPerRoot {
  private final Map<GitRepository, FetchResult> errorsPerRoot = Maps.newLinkedHashMap();
  private final AtomicBoolean anyProblems = new AtomicBoolean();

  public synchronized void add(GitRepository repository, FetchResult result) {
    Preconditions.checkState(errorsPerRoot.put(repository, result) == null);
    anyProblems.set(!result.result().isSuccess());
  }

  public void showProblems(Notifier notifier) {
    Map<GitRepository, FetchResult> errors;
    synchronized (this) {
      errors = Maps.newLinkedHashMap(errorsPerRoot);
    }

    if (anyProblems.get()) {
      boolean anyNotAuthorized = false;
      boolean anyError = false;
      StringBand message = new StringBand();
      for (Entry<GitRepository, FetchResult> entry : errors.entrySet()) {
        message.append(Html.BR);
        String boldName = GitUIUtil.bold(GtUtil.name(entry.getKey()));
        FetchResult entryResult = entry.getValue();
        if (entryResult.result().isCancelled()) {
          message.append(boldName).append(": cancelled by user").append(entryResult.result().getAdditionalInfo());
        } else if (entryResult.result().isNotAuthorized()) {
          message.append(boldName).append(": couldn't authorize").append(entryResult.result().getAdditionalInfo());
          anyNotAuthorized = true;
        } else if (entryResult.result().isError()) {
          message.append(boldName).append(": fetch failed").append(entryResult.result().getAdditionalInfo());
          anyError = true;
        }
      }
      if (anyError || anyNotAuthorized) {
        notifier.fetchError("Fetch problems:" + Html.BR + message.toString());
      } else {
        notifier.fetchWarning("Fetch problems:", message.toString());
      }
    }
  }
}

@@ -223,24 +223,51 @@
 .Map.Entry;%0A
+import java.util.Optional;%0A
 import java.
@@ -1327,24 +1327,84 @@
 getValue();%0A
+        Optional%3CString%3E additionalInfo = Optional.empty();%0A
         if (
@@ -1505,24 +1505,45 @@
 y user%22)
-.append(
+;%0A          additionalInfo = 
 entryRes
@@ -1566,33 +1566,32 @@
 AdditionalInfo()
-)
 ;%0A        %7D else
@@ -1702,24 +1702,45 @@
 horize%22)
-.append(
+;%0A          additionalInfo = 
 entryRes
@@ -1763,33 +1763,32 @@
 AdditionalInfo()
-)
 ;%0A          anyN
@@ -1920,24 +1920,45 @@
 failed%22)
-.append(
+;%0A          additionalInfo = 
 entryRes
@@ -1989,17 +1989,16 @@
 alInfo()
-)
 ;%0A      
@@ -2024,24 +2024,75 @@
 ;%0A        %7D%0A
+        additionalInfo.ifPresent(message::append);%0A
       %7D%0A    

Handle missing additional info