package com.hubspot.singularity.data.history;

import java.util.Collections;
import java.util.List;

import com.google.common.base.Optional;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.hubspot.mesos.JavaUtils;
import com.hubspot.singularity.OrderDirection;
import com.hubspot.singularity.SingularityRequestHistory;
import com.hubspot.singularity.data.RequestManager;

@Singleton
public class RequestHistoryHelper extends BlendedHistoryHelper<SingularityRequestHistory, String> {

  private final RequestManager requestManager;
  private final HistoryManager historyManager;

  @Inject
  public RequestHistoryHelper(RequestManager requestManager, HistoryManager historyManager) {
    this.requestManager = requestManager;
    this.historyManager = historyManager;
  }

  @Override
  protected List<SingularityRequestHistory> getFromZk(String requestId) {
    List<SingularityRequestHistory> requestHistory = requestManager.getRequestHistory(requestId);

    Collections.sort(requestHistory);

    return requestHistory;
  }

  @Override
  protected List<SingularityRequestHistory> getFromHistory(String requestId, int historyStart, int numFromHistory) {
    return historyManager.getRequestHistory(requestId, Optional.of(OrderDirection.DESC), historyStart, numFromHistory);
  }

  public Optional<SingularityRequestHistory> getFirstHistory(String requestId) {
    Optional<SingularityRequestHistory> firstHistory = JavaUtils.getFirst(historyManager.getRequestHistory(requestId, Optional.of(OrderDirection.ASC), 0, 1));

    if (firstHistory.isPresent()) {
      return firstHistory;
    }

    return JavaUtils.getLast(getFromZk(requestId));
  }

  public Optional<SingularityRequestHistory> getLastHistory(String requestId) {
    Optional<SingularityRequestHistory> lastHistory = JavaUtils.getFirst(getFromZk(requestId));

    if (lastHistory.isPresent()) {
      return lastHistory;
    }

    return JavaUtils.getFirst(historyManager.getRequestHistory(requestId, Optional.of(OrderDirection.DESC), 0, 1));
  }

}

@@ -70,16 +70,45 @@
 ctions;%0A
+import java.util.Comparator;%0A
 import j
@@ -1078,24 +1078,439 @@
 story;%0A  %7D%0A%0A
+  @Override%0A  protected boolean queryUsesZkFirst(String id) %7B%0A    return false;%0A  %7D%0A%0A  @Override%0A  protected Comparator%3CSingularityRequestHistory%3E getComparator(String id) %7B%0A    return new Comparator%3CSingularityRequestHistory%3E() %7B%0A      @Override public int compare(SingularityRequestHistory o1, SingularityRequestHistory o2) %7B%0A        return Long.compare(o2.getCreatedAt(), o1.getCreatedAt());%0A      %7D%0A    %7D;%0A  %7D%0A%0A
   @Override%0A

make sure request history always in correct order