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

import cz.moneta.test.harness.support.rest.RawRestRequest;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Optional;

public class FileReader {
    @Deprecated(forRemoval = true)
    public static String readFileFromResourcesOld(String path) {
        return Optional.ofNullable(RawRestRequest.Builder.class.getClassLoader().getResource(path))
                .map(url -> {
                    try {
                        return url.toURI();
                    } catch (URISyntaxException e) {
                        throw new IllegalArgumentException("Resource not found: " + path);
                    }
                })
                .map(Paths::get)
                .map(p -> {
                    try {
                        return Files.lines(p);
                    } catch (IOException e) {
                        throw new IllegalStateException("Resource not read from file: " + path);
                    }
                })
                .orElseThrow(() -> new IllegalArgumentException("Resource not found: " + path))
                .reduce(new StringBuilder(), StringBuilder::append, StringBuilder::append)
                .toString();
    }

    public static String readFileFromResources(String path) {
        return Optional.ofNullable(RawRestRequest.Builder.class.getClassLoader().getResource(path))
                .map(url -> {
                    try {
                        return IOUtils.toString(url, Charset.defaultCharset());
                    } catch (IOException e) {
                        throw new IllegalArgumentException("Resource cannot be read: " + path);
                    }
                })
                .orElseThrow(() -> new IllegalArgumentException("Resource not found: " + path));
    }
}
