/*
 * https://webfolder.io/license.html
 */
package io.webfolder.cdp;

import static java.lang.ProcessBuilder.Redirect.DISCARD;
import static java.lang.System.getProperty;
import static java.util.Collections.sort;
import static java.util.stream.Collectors.toList;

import java.util.List;

import io.github.classgraph.ClassGraph;
import io.github.classgraph.ScanResult;
import me.tongfei.progressbar.ProgressBar;

public class ExecuteAllExamples {

    private static final String CP = getProperty("java.class.path");

    public static void main(String[] args) throws Throwable {
        ClassGraph graph = new ClassGraph();
        ScanResult result = graph.acceptPackages(ExecuteAllExamples.class.getPackage().getName())
                                 .enableAnnotationInfo()
                                 .scan();
        List<String> examples = result.getClassesWithAnnotation(Example.class)
                                      .stream()
                                      .map(ci -> ci.getName())
                                      .collect(toList());
        sort(examples);
        try (ProgressBar bar = new ProgressBar("Examples", examples.size())) {
            for (String example : examples) {
                bar.step();
                bar.setExtraMessage(example.substring(example.lastIndexOf(".") + 1, example.length()));
                ProcessBuilder builder = new ProcessBuilder("java", "--class-path", CP, example);
                builder.redirectOutput(DISCARD);
                int exitCode = builder.start()
                        .waitFor();
                assert exitCode == 0;
            }
        }
    }
}