/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * 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.facebook.buck.core.rules.impl;

import com.facebook.buck.core.artifact.Artifact;
import com.facebook.buck.core.artifact.ArtifactFilesystem;
import com.facebook.buck.core.artifact.BoundArtifact;
import com.facebook.buck.core.build.buildable.context.BuildableContext;
import com.facebook.buck.core.build.context.BuildContext;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.rulekey.AddToRuleKey;
import com.facebook.buck.core.rules.BuildRule;
import com.facebook.buck.core.rules.BuildRuleResolver;
import com.facebook.buck.core.rules.actions.Action;
import com.facebook.buck.core.rules.analysis.RuleAnalysisResult;
import com.facebook.buck.core.rules.attr.SupportsInputBasedRuleKey;
import com.facebook.buck.core.rules.providers.collect.ProviderInfoCollection;
import com.facebook.buck.core.sourcepath.SourcePath;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.step.Step;
import com.facebook.buck.step.impl.ActionExecutionStep;
import com.facebook.buck.util.MoreSuppliers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables;
import java.util.Objects;
import java.util.Optional;
import java.util.SortedSet;
import java.util.function.Supplier;
import javax.annotation.Nullable;

/**
 * This represents the {@link RuleAnalysisResult} in the modern action framework as a legacy {@link
 * BuildRule} so that existing architecture can use them.
 *
 * <p>TODO(bobyf): figure out how to propagate provider info from here TODO(bobyf): make this a
 * {@link com.facebook.buck.rules.modern.ModernBuildRule}
 */
public class RuleAnalysisLegacyBuildRuleView extends AbstractBuildRule
    implements SupportsInputBasedRuleKey {

  private final String type;
  @AddToRuleKey private final Optional<Action> action;
  private Supplier<SortedSet<BuildRule>> buildDepsSupplier;
  private BuildRuleResolver ruleResolver;
  private final ProviderInfoCollection providerInfoCollection;

  /**
   * @param type the type of this {@link BuildRule}
   * @param buildTarget the {@link BuildTarget} of this analysis rule
   * @param action the action of the result for which we want to provide the {@link BuildRule} view
   * @param ruleResolver the current {@link BuildRuleResolver} to query dependent rules
   * @param projectFilesystem the filesystem
   * @param providerInfoCollection the providers returned by this build target
   */
  public RuleAnalysisLegacyBuildRuleView(
      String type,
      BuildTarget buildTarget,
      Optional<Action> action, // TODO change this to iterable once we allow multiple outputs
      BuildRuleResolver ruleResolver,
      ProjectFilesystem projectFilesystem,
      ProviderInfoCollection providerInfoCollection) {
    super(buildTarget, projectFilesystem);
    this.type = type;
    this.action = action;
    this.ruleResolver = ruleResolver;
    this.providerInfoCollection = providerInfoCollection;
    this.buildDepsSupplier = MoreSuppliers.memoize(this::getBuildDepsSupplier);
  }

  @Override
  public String getType() {
    return type;
  }

  @Override
  public SortedSet<BuildRule> getBuildDeps() {
    return buildDepsSupplier.get();
  }

  private SortedSet<BuildRule> getBuildDepsSupplier() {
    return action
        .map(
            a ->
                ruleResolver.getAllRules(
                    a.getInputs().stream()
                        .map(Artifact::asBound)
                        .map(BoundArtifact::asBuildArtifact)
                        .filter(Objects::nonNull)
                        .map(artifact -> artifact.getSourcePath().getTarget())
                        .collect(ImmutableList.toImmutableList())))
        .orElse(ImmutableSortedSet.of());
  }

  @Override
  public ImmutableList<? extends Step> getBuildSteps(
      BuildContext context, BuildableContext buildableContext) {
    // TODO(bobyf): refactor build engine and build rules to not require getBuildSteps but runs
    // actions

    if (!action.isPresent()) {
      return ImmutableList.of();
    }

    for (Artifact artifact : action.get().getOutputs()) {
      buildableContext.recordArtifact(
          Objects.requireNonNull(artifact.asBound().asBuildArtifact())
              .getSourcePath()
              .getResolvedPath());
    }
    return ImmutableList.of(
        new ActionExecutionStep(action.get(), new ArtifactFilesystem(getProjectFilesystem())));
  }

  @Nullable
  @Override
  public SourcePath getSourcePathToOutput() {
    // TODO: support multiple outputs
    return action
        .map(a -> Iterables.getOnlyElement(a.getOutputs()).asBound().getSourcePath())
        .orElse(null);
  }

  @Override
  public boolean isCacheable() {
    return true;
  }

  @Override
  public void updateBuildRuleResolver(BuildRuleResolver ruleResolver) {
    this.ruleResolver = ruleResolver;
    this.buildDepsSupplier = MoreSuppliers.memoize(this::getBuildDepsSupplier);
  }

  /** @return the {@link ProviderInfoCollection} returned from rule analysis */
  public ProviderInfoCollection getProviderInfos() {
    return providerInfoCollection;
  }
}

@@ -1859,16 +1859,38 @@
 tional;%0A
+import java.util.Set;%0A
 import j
@@ -5163,24 +5163,168 @@
 oOutput() %7B%0A
+    Set%3CArtifact%3E artifacts = providerInfoCollection.getDefaultInfo().defaultOutputs();%0A    if (artifacts.isEmpty()) %7B%0A      return null;%0A    %7D%0A
     // TODO:
@@ -5363,33 +5363,8 @@
 turn
- action%0A        .map(a -%3E
  Ite
@@ -5386,29 +5386,24 @@
 lement(a
-.getOutputs()
+rtifacts
 ).asBoun
@@ -5425,31 +5425,8 @@
 th()
-)%0A        .orElse(null)
 ;%0A  

Change getSourcePathToOutput to get output from provider instead of action