// Copyright 2015 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.skyframe;

import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Nullable;

/**
 * {@link WalkableGraph} that looks nodes up in a {@link QueryableGraph}.
 */
public class DelegatingWalkableGraph implements WalkableGraph {
  private final QueryableGraph graph;

  public DelegatingWalkableGraph(QueryableGraph graph) {
    this.graph = graph;
  }

  private NodeEntry getEntry(SkyKey key) {
    NodeEntry entry = Preconditions.checkNotNull(graph.get(key), key);
    Preconditions.checkState(entry.isDone(), "%s %s", key, entry);
    return entry;
  }

  private Map<SkyKey, NodeEntry> getEntries(Iterable<SkyKey> keys) {
    Map<SkyKey, NodeEntry> result = graph.getBatch(keys);
    Preconditions.checkState(result.size() == Iterables.size(keys), "%s %s", keys, result);
    for (Map.Entry<SkyKey, NodeEntry> entry : result.entrySet()) {
      Preconditions.checkState(entry.getValue().isDone(), entry);
    }
    return result;
  }

  @Override
  public boolean exists(SkyKey key) {
    NodeEntry entry = graph.get(key);
    return entry != null && entry.isDone();
  }

  @Nullable
  @Override
  public SkyValue getValue(SkyKey key) {
    return getEntry(key).getValue();
  }

  private static final Function<NodeEntry, SkyValue> GET_SKY_VALUE_FUNCTION =
      new Function<NodeEntry, SkyValue>() {
        @Nullable
        @Override
        public SkyValue apply(NodeEntry entry) {
          return entry.isDone() ? entry.getValue() : null;
        }
      };

  @Override
  public Map<SkyKey, SkyValue> getSuccessfulValues(Iterable<SkyKey> keys) {
    return Maps.filterValues(Maps.transformValues(graph.getBatch(keys), GET_SKY_VALUE_FUNCTION),
        Predicates.notNull());
  }

  @Override
  public Map<SkyKey, Exception> getMissingAndExceptions(Iterable<SkyKey> keys) {
    Map<SkyKey, Exception> result = new HashMap<>();
    Map<SkyKey, NodeEntry> graphResult = graph.getBatch(keys);
    for (SkyKey key : keys) {
      NodeEntry nodeEntry = graphResult.get(key);
      if (nodeEntry == null || !nodeEntry.isDone()) {
        result.put(key, null);
      } else {
        ErrorInfo errorInfo = nodeEntry.getErrorInfo();
        if (errorInfo != null) {
          result.put(key, errorInfo.getException());
        }
      }
    }
    return result;
  }

  @Nullable
  @Override
  public Exception getException(SkyKey key) {
    ErrorInfo errorInfo = getEntry(key).getErrorInfo();
    return errorInfo == null ? null : errorInfo.getException();
  }

  private static final Function<NodeEntry, Iterable<SkyKey>> GET_DIRECT_DEPS_FUNCTION =
      new Function<NodeEntry, Iterable<SkyKey>>() {
        @Override
        public Iterable<SkyKey> apply(NodeEntry entry) {
          return entry.getDirectDeps();
        }
      };

  @Override
  public Map<SkyKey, Iterable<SkyKey>> getDirectDeps(Iterable<SkyKey> keys) {
    return Maps.transformValues(getEntries(keys), GET_DIRECT_DEPS_FUNCTION);
  }

  private static final Function<NodeEntry, Iterable<SkyKey>> GET_REVERSE_DEPS_FUNCTION =
      new Function<NodeEntry, Iterable<SkyKey>>() {
        @Override
        public Iterable<SkyKey> apply(NodeEntry entry) {
          return entry.getReverseDeps();
        }
      };

  @Override
  public Map<SkyKey, Iterable<SkyKey>> getReverseDeps(Iterable<SkyKey> keys) {
    return Maps.transformValues(getEntries(keys), GET_REVERSE_DEPS_FUNCTION);
  }
}

@@ -1094,16 +1094,17 @@
 Graph %7B%0A
+%0A
   privat
@@ -1122,25 +1122,71 @@
 ryableGraph 
-g
+fullGraph;%0A  private final QueryableGraph thinG
 raph;%0A%0A  pub
@@ -1249,18 +1249,324 @@
 this
-.graph = g
+(graph, graph);%0A  %7D%0A%0A  /**%0A   * Use this constructor when you want to differentiate reads that require the node value vs reads%0A   * that only traverse dependencies.%0A   */%0A  public DelegatingWalkableGraph(QueryableGraph fullGraph, QueryableGraph thinGraph) %7B%0A    this.fullGraph = fullGraph;%0A    this.thinGraph = thinG
 raph
@@ -1664,17 +1664,21 @@
 NotNull(
-g
+fullG
 raph.get
@@ -1790,16 +1790,23 @@
 private 
+static 
 Map%3CSkyK
@@ -1844,32 +1844,54 @@
 ble%3CSkyKey%3E keys
+, QueryableGraph graph
 ) %7B%0A    Map%3CSkyK
@@ -2259,25 +2259,29 @@
 try entry = 
-g
+thinG
 raph.get(key
@@ -2863,17 +2863,21 @@
 mValues(
-g
+fullG
 raph.get
@@ -3129,33 +3129,37 @@
 %3E graphResult = 
-g
+fullG
 raph.getBatch(ke
@@ -4136,24 +4136,35 @@
 Entries(keys
+, thinGraph
 ), GET_DIREC
@@ -4597,24 +4597,35 @@
 Entries(keys
+, thinGraph
 ), GET_REVER

Use a thin graph when querying reverse deps (or others that don't need the values).