package io.quarkus.deployment.steps;

import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.BiFunction;

import org.jboss.logging.Logger;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;

import io.quarkus.bootstrap.classloading.ClassPathElement;
import io.quarkus.bootstrap.classloading.QuarkusClassLoader;
import io.quarkus.deployment.QuarkusClassWriter;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.builditem.ApplicationArchivesBuildItem;
import io.quarkus.deployment.builditem.BytecodeTransformerBuildItem;
import io.quarkus.deployment.builditem.TransformedClassesBuildItem;
import io.quarkus.deployment.index.ConstPoolScanner;

public class ClassTransformingBuildStep {

    private static final Logger log = Logger.getLogger(ClassTransformingBuildStep.class);

    @BuildStep
    TransformedClassesBuildItem handleClassTransformation(List<BytecodeTransformerBuildItem> bytecodeTransformerBuildItems,
            ApplicationArchivesBuildItem appArchives) throws ExecutionException, InterruptedException {
        if (bytecodeTransformerBuildItems.isEmpty()) {
            return new TransformedClassesBuildItem(Collections.emptyMap());
        }
        final Map<String, List<BiFunction<String, ClassVisitor, ClassVisitor>>> bytecodeTransformers = new HashMap<>(
                bytecodeTransformerBuildItems.size());
        Set<String> noConstScanning = new HashSet<>();
        Map<String, Set<String>> constScanning = new HashMap<>();
        Set<String> eager = new HashSet<>();
        for (BytecodeTransformerBuildItem i : bytecodeTransformerBuildItems) {
            bytecodeTransformers.computeIfAbsent(i.getClassToTransform(), (h) -> new ArrayList<>())
                    .add(i.getVisitorFunction());
            if (i.getRequireConstPoolEntry() == null || i.getRequireConstPoolEntry().isEmpty()) {
                noConstScanning.add(i.getClassToTransform());
            } else {
                constScanning.computeIfAbsent(i.getClassToTransform(), (s) -> new HashSet<>())
                        .addAll(i.getRequireConstPoolEntry());
            }
            if (i.isEager()) {
                eager.add(i.getClassToTransform());
            }
        }
        QuarkusClassLoader cl = (QuarkusClassLoader) Thread.currentThread().getContextClassLoader();
        Map<String, Path> transformedToArchive = new ConcurrentHashMap<>();
        // now copy all the contents to the runner jar
        // we also record if any additional archives needed transformation
        // when we copy these archives we will remove the problematic classes
        final ExecutorService executorPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        final ConcurrentLinkedDeque<Future<TransformedClassesBuildItem.TransformedClass>> transformed = new ConcurrentLinkedDeque<>();
        try {
            ClassLoader transformCl = Thread.currentThread().getContextClassLoader();
            for (Map.Entry<String, List<BiFunction<String, ClassVisitor, ClassVisitor>>> entry : bytecodeTransformers
                    .entrySet()) {
                String className = entry.getKey();
                String classFileName = className.replace(".", "/") + ".class";
                List<ClassPathElement> archives = cl.getElementsWithResource(classFileName);
                if (!archives.isEmpty()) {
                    ClassPathElement classPathElement = archives.get(0);
                    Path jar = classPathElement.getRoot();
                    if (jar == null) {
                        log.warnf("Cannot transform %s as it's containing application archive could not be found.",
                                entry.getKey());
                        continue;
                    }
                    List<BiFunction<String, ClassVisitor, ClassVisitor>> visitors = entry.getValue();
                    transformedToArchive.put(classFileName, jar);
                    transformed.add(executorPool.submit(new Callable<TransformedClassesBuildItem.TransformedClass>() {
                        @Override
                        public TransformedClassesBuildItem.TransformedClass call() throws Exception {
                            ClassLoader old = Thread.currentThread().getContextClassLoader();
                            try {
                                Thread.currentThread().setContextClassLoader(transformCl);
                                byte[] classData = classPathElement.getResource(classFileName).getData();
                                Set<String> constValues = constScanning.get(className);
                                if (constValues != null && !noConstScanning.contains(className)) {
                                    if (!ConstPoolScanner.constPoolEntryPresent(classData, constValues)) {
                                        return null;
                                    }
                                }
                                ClassReader cr = new ClassReader(classData);
                                ClassWriter writer = new QuarkusClassWriter(cr,
                                        ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
                                ClassVisitor visitor = writer;
                                for (BiFunction<String, ClassVisitor, ClassVisitor> i : visitors) {
                                    visitor = i.apply(className, visitor);
                                }
                                cr.accept(visitor, 0);
                                return new TransformedClassesBuildItem.TransformedClass(className, writer.toByteArray(),
                                        classFileName, eager.contains(className));
                            } finally {
                                Thread.currentThread().setContextClassLoader(old);
                            }
                        }
                    }));
                } else {
                    log.warnf("Cannot transform %s as it's containing application archive could not be found.",
                            entry.getKey());
                }
            }

        } finally {
            executorPool.shutdown();
        }
        Map<Path, Set<TransformedClassesBuildItem.TransformedClass>> transformedClassesByJar = new HashMap<>();
        if (!transformed.isEmpty()) {
            for (Future<TransformedClassesBuildItem.TransformedClass> i : transformed) {
                final TransformedClassesBuildItem.TransformedClass res = i.get();
                if (res != null) {
                    transformedClassesByJar.computeIfAbsent(transformedToArchive.get(res.getFileName()), (a) -> new HashSet<>())
                            .add(res);
                }
            }
        }
        return new TransformedClassesBuildItem(transformedClassesByJar);
    }

}

@@ -31,16 +31,70 @@
 steps;%0A%0A
+import java.io.File;%0Aimport java.io.FileOutputStream;%0A
 import j
@@ -781,16 +781,60 @@
 riter;%0A%0A
+import io.quarkus.bootstrap.BootstrapDebug;%0A
 import i
@@ -6145,24 +6145,1158 @@
 isitor, 0);%0A
+                                byte%5B%5D data = writer.toByteArray();%0A                                if (BootstrapDebug.DEBUG_TRANSFORMED_CLASSES_DIR != null) %7B%0A                                    File debugPath = new File(BootstrapDebug.DEBUG_TRANSFORMED_CLASSES_DIR);%0A                                    if (!debugPath.exists()) %7B%0A                                        debugPath.mkdir();%0A                                    %7D%0A                                    File classFile = new File(debugPath, className.replace(%22.%22, %22/%22) + %22.class%22);%0A                                    classFile.getParentFile().mkdirs();%0A                                    try (FileOutputStream classWriter = new FileOutputStream(classFile)) %7B%0A                                        classWriter.write(data);%0A                                    %7D catch (Exception e) %7B%0A                                        log.errorf(e, %22Failed to write transformed class %25s%22, className);%0A                                    %7D%0A                                    log.infof(%22Wrote transformed class to %25s%22, classFile.getAbsolutePath());%0A                                %7D%0A
             
@@ -7382,36 +7382,20 @@
 ssName, 
-writer.toByteArray()
+data
 ,%0A      

Allow transformed classes to be dumped