package click.kamil.springstatemachineexporter.ast.common;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class FileUtils {
    public static List<Path> findFilesWithExtension(Set<Path> startDirs, String extension) throws RuntimeException {
        return findFilesWithExtension(startDirs, extension, Collections.emptySet());
    }

    public static List<Path> findFilesWithExtension(Set<Path> startDirs, String extension, Set<String> ignorePatterns) throws RuntimeException {
        List<PathMatcher> matchers = ignorePatterns.stream()
                .map(p -> FileSystems.getDefault().getPathMatcher("glob:" + p))
                .collect(Collectors.toList());

        try (Stream<Path> paths = startDirs.stream()
                .flatMap(startDir -> {
                    try {
                        return Files.walk(startDir);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                })) {
            return paths
                    .filter(p -> Files.isRegularFile(p) && p.toString().endsWith(extension))
                    .filter(p -> matchers.stream().noneMatch(m -> m.matches(p)))
                    .map(Path::toAbsolutePath)
                    .map(Path::normalize)
                    .distinct()
                    .collect(Collectors.toList());
        }
    }
}
