package com.braintree.graphql;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;


public class BrainTreeGraphQLSchemaReaderUtil {

    private static final String PREFIX_PATH = "graphql/";
    private static final String SUFFIX_PATH = ".graphql";

    private static final String EXCEPTION_MESSAGE = "Can not find query file: ";

    private BrainTreeGraphQLSchemaReaderUtil() {
        //empty to avoid instantiating this constant class
    }

    public static String getSchemaFromFileName(final String filename) throws IOException {
        final InputStream inputStream = BrainTreeGraphQLSchemaReaderUtil.class.getClassLoader()
            .getResourceAsStream(PREFIX_PATH + filename + SUFFIX_PATH);
        if (inputStream == null) {
            throw new IOException(EXCEPTION_MESSAGE + PREFIX_PATH + filename + SUFFIX_PATH);
        }
        return readString(inputStream);
    }

    private static String readString(InputStream inputStream) {
        return new BufferedReader(
            new InputStreamReader(inputStream, StandardCharsets.UTF_8))
            .lines()
            .collect(Collectors.joining("\n"));

    }

}
