package cz.moneta.test.harness.support.selenium;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.remote.FileDetector;

import java.io.File;
import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Collector;

public class ClasspathFileDetector implements FileDetector {

    private static final Logger LOGGER = LogManager.getLogger(ClasspathFileDetector.class);

    private static final Collector<CharSequence, StringBuilder, String> PATH_COLLECTOR = Collector.of(
            StringBuilder::new,
            StringBuilder::append,
            StringBuilder::append,
            StringBuilder::toString);

    @Override
    public File getLocalFile(CharSequence... keys) {
        LOGGER.debug(String.format("About to resolve file on classpath for keys: %s", keys));
        return Optional.ofNullable(keys)
                .map(k -> {
                    String path = Arrays.stream(k).collect(PATH_COLLECTOR);
                    LOGGER.debug("Path: {}", path);
                    return path;
                })
                .map(p -> {
                    File file = new File(p);
                    LOGGER.debug("File exists: {}", file.exists());
                    LOGGER.debug("File isFile: {}", file.isFile());
                    return file;
                })
                .filter(File::exists)
                .filter(File::isFile)
                .orElse(null);
    }
}
