/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 org.apache.beam.runners.core.construction;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.beam.model.pipeline.v1.RunnerApi;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableList;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableMap;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Lists;

/**
 * A default artifact resolver. This resolver applies {@link ResolutionFn} in the reversed order
 * they registered i.e. the function registered later overrides the earlier one if they resolve the
 * same artifact.
 */
public class DefaultArtifactResolver implements ArtifactResolver {
  public static final ArtifactResolver INSTANCE = new DefaultArtifactResolver();

  private List<ResolutionFn> fns =
      Lists.newArrayList(
          (info) -> {
            if (BeamUrns.getUrn(RunnerApi.StandardArtifacts.Types.FILE).equals(info.getTypeUrn())) {
              return Optional.of(ImmutableList.of(info));
            } else {
              return Optional.empty();
            }
          });

  private Function<RunnerApi.ArtifactInformation, Stream<RunnerApi.ArtifactInformation>> resolver =
      (info) -> {
        for (ResolutionFn fn : Lists.reverse(fns)) {
          Optional<List<RunnerApi.ArtifactInformation>> resolved = fn.resolve(info);
          if (resolved.isPresent()) {
            return resolved.get().stream();
          }
        }
        throw new RuntimeException(String.format("Cannot resolve artifact information: %s", info));
      };

  @Override
  public void register(ResolutionFn fn) {
    fns.add(fn);
  }

  @Override
  public List<RunnerApi.ArtifactInformation> resolveArtifacts(
      List<RunnerApi.ArtifactInformation> artifacts) {
    for (ResolutionFn fn : Lists.reverse(fns)) {
      List<RunnerApi.ArtifactInformation> moreResolved = new ArrayList<>();
      for (RunnerApi.ArtifactInformation artifact : artifacts) {
        Optional<List<RunnerApi.ArtifactInformation>> resolved = fn.resolve(artifact);
        if (resolved.isPresent()) {
          moreResolved.addAll(resolved.get());
        } else {
          moreResolved.add(artifact);
        }
      }
      artifacts = moreResolved;
    }
    return artifacts;
  }

  @Override
  public RunnerApi.Pipeline resolveArtifacts(RunnerApi.Pipeline pipeline) {
    ImmutableMap.Builder<String, RunnerApi.Environment> environmentMapBuilder =
        ImmutableMap.builder();
    for (Map.Entry<String, RunnerApi.Environment> entry :
        pipeline.getComponents().getEnvironmentsMap().entrySet()) {
      List<RunnerApi.ArtifactInformation> resolvedDependencies =
          entry
              .getValue()
              .getDependenciesList()
              .parallelStream()
              .flatMap(resolver)
              .collect(Collectors.toList());
      environmentMapBuilder.put(
          entry.getKey(),
          entry
              .getValue()
              .toBuilder()
              .clearDependencies()
              .addAllDependencies(resolvedDependencies)
              .build());
    }
    return pipeline
        .toBuilder()
        .setComponents(
            pipeline.getComponents().toBuilder().putAllEnvironments(environmentMapBuilder.build()))
        .build();
  }
}

@@ -1728,24 +1728,92 @@
 esolver();%0A%0A
+  // Not threadsafe, access through register() and regesteredFns().%0A
   private Li
@@ -1831,24 +1831,24 @@
 onFn%3E fns =%0A
-
       Lists.
@@ -2131,16 +2131,119 @@
    %7D);%0A%0A
+  private synchronized List%3CResolutionFn%3E regesteredFns() %7B%0A    return ImmutableList.copyOf(fns);%0A  %7D%0A%0A
   privat
@@ -2389,35 +2389,47 @@
 : Lists.reverse(
-fns
+regesteredFns()
 )) %7B%0A          O
@@ -2737,16 +2737,29 @@
  public 
+synchronized 
 void reg
@@ -2976,19 +2976,31 @@
 reverse(
-fns
+regesteredFns()
 )) %7B%0A   

Fix threading issue with default artifact resolver registration.