

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;
  }
}
